package com.daisuxia.web.controller;

import static com.daisuxia.web.pojo.BorrowOrder.borrowStatusMap_shenheFail;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.attach.pojo.UserInfoTude;
import com.daisuxia.attach.service.IUserInfoTudeService;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.common.Certification.IHttpCertification;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ObtainUserShortMessage;
import com.daisuxia.web.pojo.PlatfromAdvise;
import com.daisuxia.web.pojo.PublicAbout;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserAppSoftware;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserContactsVo;
import com.daisuxia.web.pojo.UserInfoImage;
import com.daisuxia.web.pojo.UserLoginLog;
import com.daisuxia.web.pojo.UserSendMessage;
import com.daisuxia.web.service.IBackConfigParamsService;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IChannelInfoService;
import com.daisuxia.web.service.IInfoIndexService;
import com.daisuxia.web.service.IJsStepRecordService;
import com.daisuxia.web.service.IObtainUserShortMessageService;
import com.daisuxia.web.service.IPlatfromAdviseService;
import com.daisuxia.web.service.IPublicAboutService;
import com.daisuxia.web.service.IPushUserService;
import com.daisuxia.web.service.IUserAppSoftwareService;
import com.daisuxia.web.service.IUserContactsService;
import com.daisuxia.web.service.IUserInfoImageService;
import com.daisuxia.web.service.IUserLoginLogService;
import com.daisuxia.web.service.IUserSendMessageService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.test.ThreadPool;
import com.daisuxia.web.util.Base64Utils;
import com.daisuxia.web.util.ConfigLoader;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.DtThread;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.TokenUtils;
import com.daisuxia.web.util.UserPushUntil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/***
 * 注册用户 用户登录 修改密码 退出登录
 * 
 * @author Administrator
 */
@Controller
public class UserLoginController extends BaseController {

	private static Logger loger = Logger.getLogger(UserLoginController.class);
	public final static String SMS_REGISTER_PREFIX = "newPhoneCode_";// Redis注册key前缀
	public final static String SMS_FIND_PREFIX = "updatePhoneCode_";// Redis找回密码key前缀
	public final static String SMS_TRADE_FIND_PREFIX = "updatePayPasswordCode_";// Redis找回交易密码key前缀
	public final static String SMS_SEND_IN_ONE_MINUTE = "SMS_SEND_IN_ONE_MINUTE_";// Redis某个手机号1分钟内已发送验证码key前缀
	public final static int INFECTIVE_SMS_TIME = 300;// 短信默认有效时间300秒
	public final static String 	REGISTER_COUNT = "registerCount_";//Redis注册次数
	public final static int 	ERROR_TIME = 60;//Redis图形验证码持续时间
	public final static String 	REGISTER_UPDATE_TIME = "registerUpdateTime_";//判断第一次注册获取短信操作时间
	public final static String 	BACK_PASS_COUNT = "backPassCount_";//找回密码发送验证码次数
	public final static String 	BACK_PASS_UPDATE_TIME = "backPassUpdateTime_";//判断第一次找回密码操作时间

	@Autowired
	private IUserService userService;
	@Autowired
	private IUserLoginLogService userLoginLogService;
	@Autowired
	private IUserSendMessageService userSendMessageService;
	@Autowired
	private IUserInfoImageService userInfoImageService;
	@Autowired
	private IPlatfromAdviseService platfromAdviseService;
	@Autowired
	private IPublicAboutService publicAboutService;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IHttpCertification httpCertification;
	@Autowired
	private IObtainUserShortMessageService obtainUserShortMessageService;
	@Autowired
	private IUserAppSoftwareService userAppSoftwareService;
	@Autowired
	private IInfoIndexService infoIndexService;
	@Autowired
	private IJsStepRecordService jsStepRecordService;
	@Autowired
	private IChannelInfoService channelInfoService;
	
	@Autowired
	private IPushUserService pushUserService;
	@Autowired
	private IUserInfoTudeService userInfoTudeService;
	@Autowired
	private IBorrowOrderService borrowOrderService;

	@Autowired
	private IBackConfigParamsService backConfigParamsService;
	private static String domainOfBucket="fs.miledai.net";
	
	static {
		PropertiesConfiguration configuration = ConfigLoader.getInstance().getConfigurations();

		if (null != configuration) {
			domainOfBucket = configuration.getString("domainOfBucket");
		}
	}
	

	/**
	 * 注册 生成手机认证码
	 */
	@RequestMapping("credit-user/reg-get-code")
	public void sendSmsCode(HttpServletRequest request, HttpServletResponse response) {
		String GENERATE_REGISTER_CODE_CHECK = "check_generate_register_code_"; // 生成手机认证码频繁标识key
		String appVersion = request.getParameter("appVersion");
		String[] str = appVersion.split("\\.");
		String v = "";
		if (str[0].toLowerCase().indexOf("V")!=-1) {
			v = str[0].substring(1, str[0].length()-1);
		}else{
			v = str[0];
		}
		/*int v2 = Integer.parseInt(v+str[1]+str[2]);
//		TODO
		if (v2>=220) {
			JSONObject json = new JSONObject();
			Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			HashMap<String, Object> map = new HashMap<String, Object>();
			String code = "-1";
			String msg = "";
			UserSendMessage message = new UserSendMessage();
			String userPhone = "";
			String captchaUrl = "";
			String type = "";  //0为进入自动发送验证码，1为点击获取验证码
			try {
				Map<String, Object> param = getParametersO(request);
				userPhone = null == param.get("phone") ? "" : param.get("phone").toString();
				type = null == param.get("type") ? "" : param.get("type").toString();
				loger.info("regest:phone=" + userPhone);
				map.put("userPhone", userPhone);
				if (StringUtils.isBlank(userPhone)) {
					code = "-1";
					msg = "请输入手机号码";
					return;
				}
				String equipmentNumber = param.get("deviceId")==null?"":param.get("deviceId").toString();
				String registerUpdateTime = jedisCluster.get(REGISTER_UPDATE_TIME+equipmentNumber); //获取redis用户第一次操作时间
				String errorCount = jedisCluster.get(REGISTER_COUNT+equipmentNumber); //获取redis用户注册验证码输错次数
				addErrorCount(errorCount, equipmentNumber, REGISTER_COUNT);
				if (StringUtils.isNotBlank(registerUpdateTime)) {
					Date date = new Date();  	
					Date date2 = DateUtil.getDate(registerUpdateTime, "yyyy-MM-dd HH:mm:ss");
					if ((date.getTime()-date2.getTime())/1000 > ERROR_TIME) {  //2次操作相隔时间大于60秒重置操作时间和操作错误次数
						jedisCluster.set(REGISTER_UPDATE_TIME+equipmentNumber,DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss")); //将第一次操作时间存入redis
						if (type.equals("0")) {
							jedisCluster.del(REGISTER_COUNT+equipmentNumber);
							errorCount = jedisCluster.get(REGISTER_COUNT+equipmentNumber);
							addErrorCount(errorCount, equipmentNumber, BACK_PASS_COUNT);
						}
					}
				}else{
					jedisCluster.set(REGISTER_UPDATE_TIME+equipmentNumber,DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss")); //将第一次操作时间存入redis
				}
				boolean isSend = true;
				if (StringUtils.isNotBlank(errorCount) && Integer.parseInt(errorCount) >= 2) {
					captchaUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/captcha.svl?RCaptchaKey=R"+request.getSession().getId();
					if (type.equals("1")) {
						if (!validateSubmitAPP(request, response)) {
							msg = "图形验证码错误";
							return;
						}
					}else{
						code = "0";
						isSend = false;
					}
				}
		
				User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
				String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度

				String content = "";
				String messageTitle = "手机短信认证";
				Map<String, String> queryParams = new HashMap<String, String>();
				queryParams.put("messageAddress", userPhone);// 手机号码
				queryParams.put("messageTitle", messageTitle);// 短信标题
				queryParams.put("messageType", "0");// 消息类型 0短信 1 站内信 2邮件
				if (user == null || user.getStatus().equals(User.USER_STATUS_THREE)) {// 被注销的账户
				    Long remainTime = checkForFront(GENERATE_REGISTER_CODE_CHECK, userPhone);
//		         	if (remainTime>0) {
//		         		code=Status.FREQUENT.getName();
//		         		json.put("time", remainTime);
//		 				msg = Status.FREQUENT.getValue();
//		 				return;
//		 			}
		         	ServiceResult serviceResult = check(request, userPhone); 
					if (serviceResult.isFail()) {
						code = "-1";
						msg = serviceResult.getMsg();
					}else {
						if (isSend) {
							// 存入redis
							jedisCluster.set(SMS_REGISTER_PREFIX + userPhone, rand);
							jedisCluster.expire(SMS_REGISTER_PREFIX + userPhone, INFECTIVE_SMS_TIME);

							content = rand + "有效时间5分钟，您正在注册" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户，如不是本人请忽略。";

							code = "0";
							msg = "成功获取验证码";
							//				UserSendMessage flagCenter = this.userSendMessageService.lastMsg(queryParams);
							//				Boolean allowSend = true;
							Date sendTime = new Date();
							if (flagCenter != null) {
						Long lastSendTime = flagCenter.getMessageCreateTime().getTime();
						Long nowTime = sendTime.getTime();

						loger.info("check phone sendmsg phone=" + userPhone + "   nowTime=" + nowTime + "  lastSendTime=" + lastSendTime + " times=" + ((nowTime - lastSendTime) / 1000 < 60));

						// 当前发送时间减上一条小于60秒，则不发送
						if ((nowTime - lastSendTime) / 1000 < 60) {
							allowSend = false;
						}
					}
					loger.info("allowSend=" + allowSend + "   phone=" + userPhone);
					if (!allowSend) {
						code = "-1";
						msg = "请一分钟后再尝试发送";
						return;
					}
							message.setPhone(userPhone);// 手机号
							message.setMessageCreateTime(sendTime);
							message.setMessageContent(content);
							message.setSendIp(this.getIpAddr(request));// 发送短信的ip
							try {
								SendSmsUtil.sendSmsCL(userPhone, content);
								loger.info("短信发送是否成功=" + code + "***" + msg);
								msg = "成功获取验证码";
							} catch (Exception e) {
								e.printStackTrace();
								code = "-1";
								msg = "信息发送失败稍后重试";
							}
							message.setMessageStatus(UserSendMessage.STATUS_SUCCESS);// 发送成功
							userSendMessageService.saveUserSendMsg(message);// 添加短息记录
							loger.info("注册验证码sendSms:" + userPhone + "-->" + rand);
						}
					}
				} else {
					if (user.getStatus().equals(User.USER_STATUS_WHITE)) {// 正常用户登录
						code = "1000";
						msg = "请输入您的登录密码";
						return;
					} else if (user.getStatus().equals(User.USER_STATUS_BLACK)) {// 黑名单用户
						code = "-1";
						msg = "黑名单用户禁止登录";
						return;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				code = "500";
				msg = "系统异常";
			} finally {
				resultMap.put("captchaUrl", captchaUrl);
				delCheckForFront(GENERATE_REGISTER_CODE_CHECK, userPhone);
				dataMap.put("item", resultMap);
				json.put("code", code);
				json.put("message", msg);
				json.put("data", dataMap);
				JSONUtil.toObjectJson(response, json.toString());
				loger.info("返回参数:" + json);
			}
		}else{*/
			sendSmsCodeV211(request, GENERATE_REGISTER_CODE_CHECK, response);
//		}
	}
	/**
	 * 注册 生成手机认证码,没有版本管理该方法在2.2.0版本之前用
	 * @param request
	 * @param GENERATE_REGISTER_CODE_CHECK
	 * @param response
	 */
	private void sendSmsCodeV211(HttpServletRequest request, String GENERATE_REGISTER_CODE_CHECK, HttpServletResponse response){
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		String code = "-1";
		String msg = "";
		UserSendMessage message = new UserSendMessage();
		String userPhone = "";
		try {
			Map<String, Object> param = getParametersO(request);
			userPhone = null == param.get("phone") ? "" : param.get("phone").toString();
			loger.info("regest:phone=" + userPhone);
			map.put("userPhone", userPhone);
			if (StringUtils.isBlank(userPhone)) {
				code = "-1";
				msg = "请输入手机号码";
				return;
			}

			User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
			String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
			String content = "";
			String messageTitle = "手机短信认证";
			Map<String, String> queryParams = new HashMap<String, String>();
			queryParams.put("messageAddress", userPhone);// 手机号码
			queryParams.put("messageTitle", messageTitle);// 短信标题
			queryParams.put("messageType", "0");// 消息类型 0短信 1 站内信 2邮件
			if (user == null || user.getStatus().equals(User.USER_STATUS_THREE)) {// 被注销的账户
			    Long remainTime = checkForFront(GENERATE_REGISTER_CODE_CHECK, userPhone);
	         	if (remainTime>0) {
	         		code=Status.FREQUENT.getName();
	         		json.put("time", remainTime);
	 				msg = Status.FREQUENT.getValue();
	 				return;
	 			}
	         	ServiceResult serviceResult = check(request, userPhone); 
				if (serviceResult.isFail()) {
					code = "-1";
					msg = serviceResult.getMsg();
				}else {
					// 存入redis
					jedisCluster.set(SMS_REGISTER_PREFIX + userPhone, rand);
					jedisCluster.expire(SMS_REGISTER_PREFIX + userPhone, INFECTIVE_SMS_TIME);
					
					content = rand + "有效时间5分钟，您正在注册" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户，如不是本人请忽略。";
					
					code = "0";
					msg = "成功获取验证码";
//				UserSendMessage flagCenter = this.userSendMessageService.lastMsg(queryParams);
//				Boolean allowSend = true;
					Date sendTime = new Date();
					/*if (flagCenter != null) {
					Long lastSendTime = flagCenter.getMessageCreateTime().getTime();
					Long nowTime = sendTime.getTime();

					loger.info("check phone sendmsg phone=" + userPhone + "   nowTime=" + nowTime + "  lastSendTime=" + lastSendTime + " times=" + ((nowTime - lastSendTime) / 1000 < 60));

					// 当前发送时间减上一条小于60秒，则不发送
					if ((nowTime - lastSendTime) / 1000 < 60) {
						allowSend = false;
					}
				}
				loger.info("allowSend=" + allowSend + "   phone=" + userPhone);
				if (!allowSend) {
					code = "-1";
					msg = "请一分钟后再尝试发送";
					return;
				}*/
					message.setPhone(userPhone);// 手机号
					message.setMessageCreateTime(sendTime);
					message.setMessageContent(content);
					message.setSendIp(this.getIpAddr(request));// 发送短信的ip
					try {
						SendSmsUtil.sendSmsCL(userPhone, content);
						loger.info("短信发送是否成功=" + code + "***" + msg);
						msg = "成功获取验证码";
					} catch (Exception e) {
						e.printStackTrace();
						code = "-1";
						msg = "信息发送失败稍后重试";
					}
					message.setMessageStatus(UserSendMessage.STATUS_SUCCESS);// 发送成功
					userSendMessageService.saveUserSendMsg(message);// 添加短息记录
					loger.info("注册验证码sendSms:" + userPhone + "-->" + rand);
				}
			} else {
				if (user.getStatus().equals(User.USER_STATUS_WHITE)) {// 正常用户登录
					code = "1000";
					msg = "请输入您的登录密码";
					return;
				} else if (user.getStatus().equals(User.USER_STATUS_BLACK)) {// 黑名单用户
					code = "-1";
					msg = "黑名单用户禁止登录";
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GENERATE_REGISTER_CODE_CHECK, userPhone);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
	
	/**
	 * 找回密码 生成手机认证码
	 */
	@RequestMapping("credit-user/reset-pwd-code")
	public void resetPwdCode(HttpServletRequest request, HttpServletResponse response) {
		String GENERATE_FIND_CODE_CHECK = "check_find_register_code_"; // 生成找回手机认证码频繁标识key
		String appVersion = request.getParameter("appVersion");
		String[] str = appVersion.split("\\.");
		String v = "";
		if (str[0].toLowerCase().indexOf("v")!=-1) {
			v = str[0].substring(1, str[0].length()-1);
		}else{
			v = str[0];
		}
		int v2 = Integer.parseInt(v+str[1]+str[2]);
		if (true) {
			JSONObject json = new JSONObject();
			Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			HashMap<String, Object> map = new HashMap<String, Object>();
			String code = "-1";
			String msg = "";
			String userPhone = "";
			String captchaUrl = "";
			String type2 = "";
			UserSendMessage message = new UserSendMessage();
			try {
				Map<String, Object> param = getParametersO(request);
				userPhone = param.get("phone").toString();
				type2 = null == param.get("type2") ? "" : param.get("type2").toString();
				if (StringUtils.isBlank(userPhone)) {
					code = "-1";
					msg = "请输入手机号码";
					return;
				}
				Long remainTime=checkForFront(GENERATE_FIND_CODE_CHECK, userPhone,60);
//				if (remainTime>0) {
//					code=Status.FREQUENT.getName();
//					json.put("time", remainTime);
//					msg = Status.FREQUENT.getValue();
//					return;
//				}

				String equipmentNumber = param.get("deviceId")==null?"":param.get("deviceId").toString();
				String registerUpdateTime = jedisCluster.get(BACK_PASS_UPDATE_TIME+equipmentNumber); //获取redis用户第一次操作时间
				String errorCount = jedisCluster.get(BACK_PASS_COUNT+equipmentNumber); //获取redis用户注册验证码输错次数
				addErrorCount(errorCount, equipmentNumber, BACK_PASS_COUNT);
				if (StringUtils.isNotBlank(registerUpdateTime)) {
					Date date = new Date();  	
					Date date2 = DateUtil.getDate(registerUpdateTime, "yyyy-MM-dd HH:mm:ss");
					if ((date.getTime()-date2.getTime())/1000 > ERROR_TIME) {  //2次操作相隔时间大于60秒重置操作时间和操作错误次数
						jedisCluster.set(BACK_PASS_UPDATE_TIME+equipmentNumber,DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss")); //将第一次操作时间存入redis
						if (type2.equals("0")) {
							jedisCluster.del(BACK_PASS_COUNT+equipmentNumber);
							errorCount = jedisCluster.get(BACK_PASS_COUNT+equipmentNumber);
							addErrorCount(errorCount, equipmentNumber, BACK_PASS_COUNT);
						}
					}
				}else{
					jedisCluster.set(BACK_PASS_UPDATE_TIME+equipmentNumber,DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss")); //将第一次操作时间存入redis
				}
				boolean isSend = true;
				if (StringUtils.isNotBlank(errorCount) && Integer.parseInt(errorCount) >= 3) {
					captchaUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/captcha.svl?RCaptchaKey=R"+request.getSession().getId();
					if (type2.equals("1")) {
						if (!validateSubmitAPP(request, response)) {
							msg = "图形验证码错误";
							return;
						}
					}else{
						code = "0";
						isSend = false;
					}
				}

				map.put("userPhone", userPhone);

				User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
				if (null == user) {
					code = "-1";
					msg = "请输入手机号码";
					return;
				}
				ServiceResult serviceResult = check(request, userPhone); 
				if (serviceResult.isFail()) {
					code = "-1";
					msg = serviceResult.getMsg();
				}else {
					if (isSend) {
						String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
						String content = "";
						String messageTitle = "手机短信认证";
						Map<String, String> queryParams = new HashMap<String, String>();
						queryParams.put("messageAddress", userPhone);// 手机号码
						queryParams.put("messageTitle", messageTitle);// 短信标题
						queryParams.put("messageType", "0");// 消息类型 0短信 1 站内信 2邮件
						if (param.containsKey("type") && param.get("type").equals("find_pwd")) {// 登录密码找回验证码
							// 存入redis
							jedisCluster.set(SMS_FIND_PREFIX + userPhone, rand);
							jedisCluster.expire(SMS_FIND_PREFIX + userPhone, INFECTIVE_SMS_TIME);

							content = rand + "有效时间5分钟，您正在找回" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户登录密码，请勿将验证码告诉他人。";
							code = "0";
							msg = "发送验证码成功";
							message.setPhone(userPhone);// 接收的用户
						} else if (param.containsKey("type") && param.get("type").equals("find_pay_pwd")) {// 交易密码找回验证码
							// 存入redis
							jedisCluster.set(SMS_TRADE_FIND_PREFIX + userPhone, rand);
							jedisCluster.expire(SMS_TRADE_FIND_PREFIX + userPhone, INFECTIVE_SMS_TIME);

							content = rand + "有效时间5分钟，您正在找回" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户交易密码，请勿将验证码告诉他人。";
							code = "0";
							msg = "发送验证码成功";
							message.setPhone(userPhone);// 接收的用户
						}
						Date sendTime = new Date();
						message.setPhone(userPhone);// 手机号
						message.setMessageCreateTime(sendTime);
						message.setMessageContent(content);
						message.setSendIp(this.getIpAddr(request));
						try {
							SendSmsUtil.sendSmsCL(userPhone, content);
							msg = "发送验证码成功";
							resultMap.put("item", "1");
						} catch (Exception e) {
							e.printStackTrace();
							code = "-1";
							msg = "信息发送失败稍后重试";
						}
						message.setMessageStatus(UserSendMessage.STATUS_SUCCESS);// 发送成功 2
						userSendMessageService.saveUserSendMsg(message);// 添加短息记录
						loger.info("找回密码sendSms:" + userPhone + "-->" + rand);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				code = "500";
				msg = "系统异常";
			} finally {
				delCheckForFront(GENERATE_FIND_CODE_CHECK, userPhone);
				resultMap.put("captchaUrl", captchaUrl);
				dataMap.put("item", resultMap);
				json.put("code", code);
				json.put("message", msg);
				json.put("data", dataMap);
				JSONUtil.toObjectJson(response, json.toString());
				loger.info("返回参数:" + dataMap);
			}
		}else{
			resetPwdCodeV211(request, GENERATE_FIND_CODE_CHECK, response);
		}
	}
	
	/**
	 * 找回密码 生成手机认证码,没有版本管理该方法在2.2.0版本之前用
	 * @param request
	 * @param GENERATE_REGISTER_CODE_CHECK
	 * @param response
	 */
	private void resetPwdCodeV211(HttpServletRequest request, String GENERATE_FIND_CODE_CHECK, HttpServletResponse response){
		JSONObject json = new JSONObject();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		String code = "-1";
		String msg = "";
		String userPhone = "";
		UserSendMessage message = new UserSendMessage();
		try {
			Map<String, Object> param = getParametersO(request);
			userPhone = param.get("phone").toString();
			if (StringUtils.isBlank(userPhone)) {
				code = "-1";
				msg = "请输入手机号码";
				return;
			}
		    Long remainTime=checkForFront(GENERATE_FIND_CODE_CHECK, userPhone,60);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			map.put("userPhone", userPhone);

			User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
			if (null == user) {
				code = "-1";
				msg = "请输入手机号码";
				return;
			}
			ServiceResult serviceResult = check(request, userPhone); 
			if (serviceResult.isFail()) {
				code = "-1";
				msg = serviceResult.getMsg();
			}else {
				String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
				String content = "";
				String messageTitle = "手机短信认证";
				Map<String, String> queryParams = new HashMap<String, String>();
				queryParams.put("messageAddress", userPhone);// 手机号码
				queryParams.put("messageTitle", messageTitle);// 短信标题
				queryParams.put("messageType", "0");// 消息类型 0短信 1 站内信 2邮件
				if (param.containsKey("type") && param.get("type").equals("find_pwd")) {// 登录密码找回验证码
					// 存入redis
					jedisCluster.set(SMS_FIND_PREFIX + userPhone, rand);
					jedisCluster.expire(SMS_FIND_PREFIX + userPhone, INFECTIVE_SMS_TIME);
					
					content = rand + "有效时间5分钟，您正在找回" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户登录密码，请勿将验证码告诉他人。";
					code = "0";
					msg = "发送验证码成功";
					message.setPhone(userPhone);// 接收的用户
				} else if (param.containsKey("type") && param.get("type").equals("find_pay_pwd")) {// 交易密码找回验证码
					// 存入redis
					jedisCluster.set(SMS_TRADE_FIND_PREFIX + userPhone, rand);
					jedisCluster.expire(SMS_TRADE_FIND_PREFIX + userPhone, INFECTIVE_SMS_TIME);
					
					content = rand + "有效时间5分钟，您正在找回" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户交易密码，请勿将验证码告诉他人。";
					code = "0";
					msg = "发送验证码成功";
					message.setPhone(userPhone);// 接收的用户
				}
				Date sendTime = new Date();
				message.setPhone(userPhone);// 手机号
				message.setMessageCreateTime(sendTime);
				message.setMessageContent(content);
				message.setSendIp(this.getIpAddr(request));
				try {
					SendSmsUtil.sendSmsCL(userPhone, content);
					msg = "发送验证码成功";
					resultMap.put("item", "1");
				} catch (Exception e) {
					e.printStackTrace();
					code = "-1";
					msg = "信息发送失败稍后重试";
				}
				message.setMessageStatus(UserSendMessage.STATUS_SUCCESS);// 发送成功 2
				userSendMessageService.saveUserSendMsg(message);// 添加短息记录
				loger.info("找回密码sendSms:" + userPhone + "-->" + rand);
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GENERATE_FIND_CODE_CHECK, userPhone);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", resultMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
	
	/***
	 * 用户注册
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("credit-user/registers")
	public void registers(HttpServletRequest request, HttpServletResponse response){
		String key = jedisCluster.get("asasas");
		if (StringUtils.isNotBlank(key)) {
			int i = Integer.parseInt(key);
			i++;
			jedisCluster.set("asasas",String.valueOf(i));
		}else{
			jedisCluster.set("asasas", "1");
		}
		System.out.println(key);
	}
	
	/***
	 * 用户注册
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("credit-user/register")
	public void register(HttpServletRequest request, HttpServletResponse response) {
		String REGISTER_USESR_CHECK = "register_check_"; // 注册验证是否重复提交
		String appVersion = request.getParameter("appVersion");
		String[] str = appVersion.split("\\.");
		String v = "";
		if (str[0].toLowerCase().indexOf("V")!=-1) {
			v = str[0].substring(1, str[0].length()-1);
		}else{
			v = str[0];
		}
		int v2 = Integer.parseInt(v+str[1]+str[2]);
		/*if (v2>=220) {
			JSONObject json = new JSONObject();
			Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			String msg = "";
			String code = "-1";
			String userPhone = "";
			try {
				userPhone = request.getParameter("phone");
				String passWord = request.getParameter("password");// 获取密码
				String smsCode = request.getParameter("code");// 获取手机验证码
				String inviteUserid = request.getParameter("invite_code");// 验证码
				String userFrom = request.getParameter("user_from");// 验证码
				String appName = request.getParameter("appName");// APP名称
				String equipmentNumber = request.getParameter("deviceId");// 设备号
				String errorCount = jedisCluster.get(REGISTER_COUNT+equipmentNumber); //获取redis用户注册验证码输错次数
				if (StringUtils.isNotBlank(errorCount) && Integer.parseInt(errorCount) >= 3) {
					if (!validateSubmitAPP(request, response)) {
						msg = "图形验证码错误";
						return;
					}
				}
				// 手机验证
				if (StringUtils.isBlank(userPhone)) {
					msg = "手机号不能为空。";
					return;
				}

				// 手机验证码验证
				if (StringUtils.isBlank(smsCode)) {
					msg = "手机验证码不能为空。";
					return;
				}

				userPhone = userPhone.trim();
				Long remainTime = checkForFront(REGISTER_USESR_CHECK, userPhone);
				if (remainTime>0) {
					code=Status.FREQUENT.getName();
					json.put("time", remainTime);
					msg = Status.FREQUENT.getValue();
					return;
				}
				String sendSmsCode = jedisCluster.get(SMS_REGISTER_PREFIX + userPhone);
				if ("".equals(smsCode)) {
					msg = "验证码不能为空";
					return;
				} else if (StringUtils.isBlank(sendSmsCode)) {
					msg = "验证码已失效，请重新获取 ";
					return;
				} else if (!sendSmsCode.equals(smsCode)) {
					msg = "验证码校验失败";
					return;
				}
				User invitetUser = null;
				User user = new User();
				AESUtil aesEncrypt = new AESUtil();
				// String userPassword = desEncrpt.decrypt(passWord,"");//解密
				String Md5 = MD5coding.MD5(aesEncrypt.encrypt(passWord, ""));// 加密

				if (passWord != null) {// 密码不为空之后 做插入操作
					user.setUserName(userPhone);// 用户名称
					user.setPassword(Md5);// 加密后的登录密码
					user.setUserPhone(userPhone);// 用户手机号码
					user.setCreateIp(this.getIpAddr(request));// 注册时的IP地址
					user.setEquipmentNumber(equipmentNumber);// 设备号
					user.setUserFrom("0");
					user.setAmountMax(String.valueOf(Constant.AMOUNT_MAX));
					user.setAmountAvailable(String.valueOf(Constant.AMOUNT_MAX));

					// 除了贷速侠的来源，其他的APP版本注册都保存用户来源
					Integer channelId = null;
					if(StringUtils.isNotBlank(appName) && !"jsxjx".equals(appName)){
						channelId = channelInfoService.findChannelIdByCode(appName);
						if(null != channelId){
							user.setUserFrom(channelId.toString());
						}
					}
					// 邀请注册时设置邀请人Id
					if (StringUtils.isNotBlank(inviteUserid)) {
						// 邀请码的验证
						Map<String, String> maps = new HashMap<String, String>();
						maps.put("id", Base64Utils.decodeStr(inviteUserid));
						invitetUser = this.userService.searchByInviteUserid(maps);
						if (invitetUser == null) {
							msg = "该邀请人不存在";
							return;
						}
						user.setInviteUserid(Base64Utils.decodeStr(inviteUserid));// 邀请好友注册的ID
					}
					else if(null != channelId){
						Integer userI = channelInfoService.findUserIdByChannelId(channelId);
						if(null != userI){
							user.setInviteUserid(userI.toString());// 邀请好友注册的ID
						}
					}

					用户来源,用于apk单独统计  2017-03-10
					if (StringUtils.isNotBlank(userFrom)) {
						user.setUserFrom(userFrom);
					}
					HashMap<String, Object> queryParams = new HashMap<String, Object>();
					queryParams.put("userPhone", userPhone);// 手机号码
					User checkUser = userService.searchUserByCheckTel(queryParams);// 查询手机号码是否存在
					if(null != checkUser){
						msg="手机号已经存在";
						return ;
					}
					userService.saveUser(user);// 注册保存新用户
					// TODO 情况1：注册成功，注入
					// request.getSession().setAttribute(Constant.FRONT_USER, user);//注册成功保存session 直接登录

					loginSucc(request, user);
					//				try {
					//					// 设置参数 可设置多个抽奖
					//					HashMap<String, String> stepMap = new HashMap<String, String>();
					//					stepMap.put("userPhone", user.getUserPhone());
					//					stepMap.put("awardType", "REGISTER");
					//					if (invitetUser != null) {
					//						stepMap.put("invitePhone", "invitetUser.getUserPhone()");
					//					}
					//					loger.info("addUserStep   REGISTER  请求参数：" + stepMap.toString());
					//					ServiceResult serviceResult = jsStepRecordService.addUserStep(stepMap);
					//					loger.info("addUserStep 抽奖返回>>>：" + serviceResult.getCode() + ":" + serviceResult.getMsg());
					//
					//				} catch (Exception e) {
					//					loger.error("addUserStep error REGISTER", e);
					//				}
					msg = "注册成功";
					code = "0";
					jedisCluster.del(REGISTER_COUNT+equipmentNumber); //注册成功重置errorCount
					HashMap<String, Object> map = new HashMap<String, Object>();
					User userNew=this.userService.searchByUserid(Integer.parseInt(user.getId()));
					map.put("userPhone", userPhone);
					resultMap.put("uid", userNew.getId());
					resultMap.put("username", userNew.getUserName());
					String realname = "";
					if (userNew.getRealname() != null) {
						realname = userNew.getRealname();
					}
					String real_verify_status = "0";
					if (userNew.getRealnameStatus() != null) {
						real_verify_status = userNew.getRealnameStatus();
					}
					String id_card = "";
					if (userNew.getIdNumber() != null) {
						id_card = userNew.getIdNumber();
					}
					resultMap.put("realname", realname);
					resultMap.put("real_verify_status", real_verify_status);
					resultMap.put("id_card", id_card);
					resultMap.put("user_sign", Base64Utils.encodeStr(userNew.getId()));
					// app用户session
					HttpSession session = request.getSession();
					String generateToken = TokenUtils.generateToken(user);
					resultMap.put("sessionid", session.getId());
				} else {
					msg = "请输入6-20位密码";
				}
			} catch (Exception e) {
				code = "500";
				msg = "系统异常，请稍后再试";
				e.printStackTrace();
			} finally {
				delCheckForFront(REGISTER_USESR_CHECK, userPhone);
				dataMap.put("item", resultMap);
				json.put("code", code);
				json.put("message", msg);
				json.put("data", dataMap);
				JSONUtil.toObjectJson(response, json.toString());
			}
		}else{*/
			registerV211(request, REGISTER_USESR_CHECK, response);
//		}
	}
	/**
	 * 用户注册 ,没有版本管理该方法在2.2.0版本之前用
	 * @param request
	 * @param REGISTER_USESR_CHECK
	 * @param response
	 */
	private void registerV211(HttpServletRequest request, String REGISTER_USESR_CHECK, HttpServletResponse response){
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String msg = "";
		String code = "-1";
		String userPhone = "";
		try {
			userPhone = request.getParameter("phone");
			String passWord = request.getParameter("password");// 获取密码
			String smsCode = request.getParameter("code");// 获取手机验证码
			String inviteUserid = request.getParameter("invite_code");// 验证码
			String userFrom = request.getParameter("user_from");// 验证码
			String appName = request.getParameter("appName");// APP名称
			String channelCode = request.getParameter("channelCode");// 渠道名称
			String clientType = request.getParameter("clientType");//客户端来源
			// 手机验证
			if (StringUtils.isBlank(userPhone)) {
				msg = "手机号不能为空。";
				return;
			}

			// 手机验证码验证
			if (StringUtils.isBlank(smsCode)) {
				msg = "手机验证码不能为空。";
				return;
			}

			userPhone = userPhone.trim();
		    Long remainTime = checkForFront(REGISTER_USESR_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			String sendSmsCode = jedisCluster.get(SMS_REGISTER_PREFIX + userPhone);
			if ("".equals(smsCode)) {
				msg = "验证码不能为空";
				return;
			} else if (StringUtils.isBlank(sendSmsCode)) {
				msg = "验证码已失效，请重新获取 ";
				return;
			} else if (!sendSmsCode.equals(smsCode)) {
				msg = "验证码校验失败";
				return;
			}
			User invitetUser = null;
			User user = new User();
			// String userPassword = desEncrpt.decrypt(passWord,"");//解密
			String Md5 = MD5coding.MD5(AESUtil.encrypt(passWord, ""));// 加密

			String equipmentNumber = request.getParameter("deviceId");// 设备号
			if (passWord != null) {// 密码不为空之后 做插入操作
				user.setUserName(userPhone);// 用户名称
				user.setPassword(Md5);// 加密后的登录密码
				user.setUserPhone(userPhone);// 用户手机号码
				user.setCreateIp(this.getIpAddr(request));// 注册时的IP地址
				user.setEquipmentNumber(equipmentNumber);// 设备号
				user.setUserFrom("0");
				user.setAmountMax(String.valueOf(Constant.AMOUNT_MAX));
				user.setAmountAvailable(String.valueOf(Constant.AMOUNT_MAX));

				// 除了贷速侠的来源，其他的APP版本注册都保存用户来源
				Integer channelId = null;
				if(StringUtils.isNotBlank(channelCode)) {
					channelId = channelInfoService.findChannelIdByCode(channelCode);
					if (null != channelId) {
						user.setUserFrom(channelId.toString());
					}else {
						loger.info("注册渠道号未找到:"+channelCode);
					}
				}else {
					loger.error("无此渠道:"+channelCode);
				}
				if(StringUtils.isNotBlank(appName) && !"jsxjx".equals(appName)){
					user.setTgFlag(appName);
					if (StringUtils.isNotBlank(clientType)) {
						user.setTgFlag(appName+"-"+clientType);
					}
				}
				// 邀请注册时设置邀请人Id
				if (StringUtils.isNotBlank(inviteUserid)) {
					// 邀请码的验证
					Map<String, String> maps = new HashMap<String, String>();
					maps.put("id", Base64Utils.decodeStr(inviteUserid));
					invitetUser = this.userService.searchByInviteUserid(maps);
					if (invitetUser == null) {
						msg = "该邀请人不存在";
						return;
					}
					user.setInviteUserid(Base64Utils.decodeStr(inviteUserid));// 邀请好友注册的ID
				}
				else if(null != channelId){
					Integer userI = channelInfoService.findUserIdByChannelId(channelId);
					if(null != userI){
						user.setInviteUserid(userI.toString());// 邀请好友注册的ID
					}
				}
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
				queryParams.put("userPhone", userPhone);// 手机号码
				User checkUser = userService.searchUserByCheckTel(queryParams);// 查询手机号码是否存在
				if(null != checkUser){
					msg="手机号已经存在";
					return ;
				}
				userService.saveUser(user);// 注册保存新用户
				// TODO 情况1：注册成功，注入
				// request.getSession().setAttribute(Constant.FRONT_USER, user);//注册成功保存session 直接登录

				loginSucc(request, user);
//				try {
//					// 设置参数 可设置多个抽奖
//					HashMap<String, String> stepMap = new HashMap<String, String>();
//					stepMap.put("userPhone", user.getUserPhone());
//					stepMap.put("awardType", "REGISTER");
//					if (invitetUser != null) {
//						stepMap.put("invitePhone", "invitetUser.getUserPhone()");
//					}
//					loger.info("addUserStep   REGISTER  请求参数：" + stepMap.toString());
//					ServiceResult serviceResult = jsStepRecordService.addUserStep(stepMap);
//					loger.info("addUserStep 抽奖返回>>>：" + serviceResult.getCode() + ":" + serviceResult.getMsg());
//
//				} catch (Exception e) {
//					loger.error("addUserStep error REGISTER", e);
//				}
				msg = "注册成功";
				code = "0";
				HashMap<String, Object> map = new HashMap<String, Object>();
				User userNew=this.userService.searchByUserid(Integer.parseInt(user.getId()));
				map.put("userPhone", userPhone);
				resultMap.put("uid", userNew.getId());
				resultMap.put("username", userNew.getUserName());
				String realname = "";
				if (userNew.getRealname() != null) {
					realname = userNew.getRealname();
				}
				String real_verify_status = "0";
				if (userNew.getRealnameStatus() != null) {
					real_verify_status = userNew.getRealnameStatus();
				}
				String id_card = "";
				if (userNew.getIdNumber() != null) {
					id_card = userNew.getIdNumber();
				}
				resultMap.put("realname", realname);
				resultMap.put("real_verify_status", real_verify_status);
				resultMap.put("id_card", id_card);
				resultMap.put("user_sign", Base64Utils.encodeStr(userNew.getId()));
				// app用户session
				HttpSession session = request.getSession();
				String generateToken = TokenUtils.generateToken(user);
				resultMap.put("sessionid", session.getId());
			} else {
				msg = "请输入6-20位密码";
			}
		} catch (Exception e) {
			code = "500";
			msg = "系统异常，请稍后再试";
			e.printStackTrace();
		} finally {
			delCheckForFront(REGISTER_USESR_CHECK, userPhone);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * goto登录
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("credit-user/login")
	public void login(HttpServletRequest request, HttpServletResponse response) {
		String LOGIN_USESR_CHECK = "login_check_"; // 登录验证是否重复提交
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String code = "-1";
		String msg = "";
		HttpSession session = request.getSession();
		String equipmentNumber = "";
		try {
			HashMap<String, Object> param = this.getParametersO(request);
			equipmentNumber = request.getParameter("deviceId");// 设备号
			if (!param.containsKey("username")) {
				code = "-1";
				msg = "用户名不能为空";
				return;
			}
			if (!param.containsKey("password")) {
				code = "-1";
				msg = "密码不能为空";
				return;
			}
			String username = param.get("username").toString();
			String password = param.get("password").toString();
			AESUtil aesEncrypt = new AESUtil();
			String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(password, ""));// 加密
			param.put("username", username);
			param.put("password", checkPassWord);
			User user = userService.searchUserByLogin(param);// 登录
			if (null != user) {
				if (User.USER_STATUS_WHITE.equals(user.getStatus())) {// 正常用户登录
					if (checkPassWord.equals(user.getPassword())) {
						loginSucc(request,user);
						// 登录成功
						code = "0";
						msg = "登录成功";
						resultMap.put("uid", user.getId());
						resultMap.put("username", user.getUserName());
						String realname = "";
						if (user.getRealname() != null) {
							realname = user.getRealname();
						}
						resultMap.put("realname", realname);
						String generateToken = TokenUtils.generateToken(user);
						resultMap.put("token", generateToken);
						resultMap.put("sessionid", session.getId());
						Map<String, String> params = new HashMap<String, String>();
						params.put("deviceId", equipmentNumber);
						params.put("userName", user.getUserName());
						UserLoginLog loginLog = this.userLoginLogService.selectByParams(params);// 查询是否有登录记录
						if (loginLog == null) {
							loginLog = new UserLoginLog();
							loginLog.setUserId(user.getId());
							loginLog.setUserName(user.getUserName());
							loginLog.setPassword(user.getPassword());
							loginLog.setLoginTime(new Date());// 登录时间
							loginLog.setLoginIp(this.getIpAddr(request));// 登录IP
							Date effTime = DateUtil.addDay(new Date(), 3);// token有效时间
							loginLog.setEffTime(effTime);
							loginLog.setToken(generateToken);// 保存token
							loginLog.setEquipmentNumber(equipmentNumber);// 保存设备号
							userLoginLogService.saveUserLoginLog(loginLog);// 新增记录
						} else {
							if (loginLog.getUserId().equals(user.getId())) {
								loginLog.setUserId(user.getId());
							}
							loginLog.setUserName(user.getUserName());
							loginLog.setPassword(user.getPassword());
							loginLog.setLoginTime(new Date());// 登录时间
							loginLog.setLoginIp(this.getIpAddr(request));// 登录IP
							Date effTime = DateUtil.addDay(new Date(), 3);// token有效时间
							loginLog.setEffTime(effTime);
							loginLog.setToken(generateToken);// 保存token
							loginLog.setEquipmentNumber(equipmentNumber);// 保存设备号
							userLoginLogService.updateUserLoginLog(loginLog);// 修改记录
						}
					} else if (user.getStatus().equals(User.USER_STATUS_BLACK)) {// 黑名单用户
						code = "-1";
						msg = "密码不正确，请重新输入。";
					}
				} else {
					code = "-1";
					msg = "黑名单用户禁止登录";
				}
			} else {
				code = "-1";
				msg = "你输入的用户或密码不正确，请重新输入。";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(LOGIN_USESR_CHECK, equipmentNumber);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
	
	//将用户输错密码次数放入redis
	private void addErrorCount(String errorCount, String equipmentNumber, String key){
		if (StringUtils.isNotBlank(errorCount)) {
			int i = Integer.parseInt(errorCount);
			i++;
			jedisCluster.set(key+equipmentNumber, String.valueOf(i));
		}else{
			jedisCluster.set(key+equipmentNumber, "1");
		}
	}

	/***
	 * 用户界面
	 */
	@RequestMapping("credit-user/get-info")
	public void userInfoIndex(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> verifyInfoMap = new HashMap<String, Object>();
		String telephone = request.getParameter("mobilePhone");
		String code = "-1";
		String msg = "获取失败";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				code = "0";
				msg = "获取成功";
				// 信用额度
				resultMap.put("userId", user.getId());// 用户ID
				String phone = user.getUserName() == null ? "" : user.getUserName();
				if (phone.length() > 4) {
					phone = phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
				}
				resultMap.put("phone", phone);// 手机号码
				String inviteCode = Base64Utils.encodeStr(user.getId()).trim();
				String invite = inviteCode.replaceAll("=", "");// 替换特殊符号
				resultMap.put("invite_code", invite);// 生成邀请码
				String realNameStatus = user.getRealnameStatus();
				verifyInfoMap.put("real_verify_status", realNameStatus);// 用户实名认证状态

				String payPasswordStatus = "0";
				if (user.getPayPassword() != null) {
					payPasswordStatus = "1";
				}
				verifyInfoMap.put("real_pay_pwd_status", payPasswordStatus);// 用户交易密码状态
				String bankStatus = "0";
				String bankUrl = "";// 未绑定跳转到银行卡页面路径

				resultMap.put("userId", user.getId());// 用户

				UserCardInfo cardInfo = userService.findUserBankCard(Integer.parseInt(user.getId()));
				HashMap<String, String> cardMap = new HashMap<String, String>();
				String card_amount = user.getAmountMax();
				String card_unused_amount = user.getAmountAvailable();
				cardMap.put("card_amount", card_amount);// 总额度
				cardMap.put("card_unused_amount", card_unused_amount);// 剩余额度
				String cardName = "";
				String cardEndNO = "";
				Map<String, Object> map = new HashMap<String, Object>();
				if (cardInfo != null) {
					// cardMap.put("card_no", cardInfo.getCard_no());//银行卡
					String card = cardInfo.getCard_no();
					cardEndNO = card.substring(card.length() - 4, card.length());// 银行卡号码
					cardName = cardInfo.getBankName();// 银行名称
					bankStatus = "1";
				}
				map.put("card_no_end", cardEndNO);
				map.put("bank_name", cardName);
				verifyInfoMap.put("real_bind_bank_card_status", bankStatus);// 用户银行卡状态
				
				//获取用户最近借款状态 代替风控
				// 如果最近借款被拒绝, 那么就显示问号, 跳转去其他的app
				// 0 不显示 1显示
				cardMap.put("risk_status","0");
				BorrowOrder bo = borrowOrderService.selectBorrowOrderNowUseId(Integer.valueOf(user.getId()));
				if(bo!=null){

					//借款审核被拒绝 添加全局控制开关 1 打开 0 关闭
					HashMap<String,Object> params = new HashMap<String,Object>();
					params.put("sysType","SYS_NOCACHE");
					params.put("syskey","SYJ_SWITCH");
					//params.put("sysName","");
					List<BackConfigParams> list = backConfigParamsService.findParams(params);
					String offon = "1";
					if(list.size()==1){
						offon = list.get(0).getSysValue();
					}

					//借款审核被拒绝
					if(borrowStatusMap_shenheFail.containsKey(bo.getStatus())
							&&"1".equals(offon)){
						cardMap.put("risk_status","1");
					}
				}

				resultMap.put("credit_info", cardMap);// 额度信息
				resultMap.put("card_info", map);// 银行卡信息

				bankUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";// 已绑定跳转银行卡页面路径
				if(null != telephone){
					resultMap.put("card_url", bankUrl + "lianlianBindCard/credit-card/firstUserBank");// 银行卡页面
				}
				else{
					resultMap.put("card_url", bankUrl + "credit-card/card-list");// 银行卡页面
				}
				resultMap.put("verify_info", verifyInfoMap);// 认证状态

				//String path = "/common/web/images/logo_share_xjx.png";
				String path = getAppConfig(request.getParameter("appName"), "XJX_LOGO");  //分享logo地址
				// 分享链接
				resultMap.put("share_body", "1分钟认证，20分钟到账，无抵押，纯信用贷。时下最流行的移动贷款APP。国内首批利用大数据、人工智能实现风控审批的信贷服务平台。");
				resultMap.put("share_logo", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + path);
				resultMap.put("share_title", getAppConfig(request.getParameter("appName"), "APP_TITLE"));
				String user_from="0";
				if(StringUtils.isNotBlank(user.getUserFrom()) && !"null".equals(user.getUserFrom())){
					user_from=user.getUserFrom();
				}
				String share_url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + "act/light-loan-xjx?invite_code=" + invite + "&user_from=" + user_from;
				if(StringUtils.isNotBlank(request.getParameter("appName"))){
					share_url +="&appName="+request.getParameter("appName");
				}
				resultMap.put("share_url", share_url);


				// zhangsh 2017年3月6日 动态客服数据
				Map<String, Object> serviceMap = new HashMap<String, Object>();
				Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.WEBSITE);
				serviceMap.put("qq_group", intervalMap.get("qq_group"));
				List<String> servicesQQ = new ArrayList<String>();
				servicesQQ.add(intervalMap.get("services_qq"));
				serviceMap.put("services_qq", servicesQQ);
				serviceMap.put("service_phone", intervalMap.get("service_phone"));
				serviceMap.put("peacetime", intervalMap.get("peacetime"));
				serviceMap.put("holiday", intervalMap.get("holiday"));

				resultMap.put("service", serviceMap);
			} else {
				code = Status.LOGIN.getName();
				msg = Status.LOGIN.getValue();
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
 			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 修改登录密码
	 */
	@RequestMapping("credit-user/change-pwd")
	public void loginUpdatePassWord(HttpServletRequest request, HttpServletResponse response) {
		String EDIT_PASSWD_CHECK = "edit_passwd_check_";
		JSONObject json = new JSONObject();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";

		AESUtil desEncrpt = new AESUtil();
		AESUtil aesEncrypt = new AESUtil();

		String flage = "false";
		String deviceId = request.getParameter("deviceId");
		try {
			
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				String passWordOld1 = request.getParameter("old_pwd");// 原密码
				String passWordNew1 = request.getParameter("new_pwd");// 新密码
				String checkPassWordOld = MD5coding.MD5(aesEncrypt.encrypt(passWordOld1, ""));// 加密

				if (user.getPassword().equals(checkPassWordOld)) {// 判断输入的密码是否与原密码一致
					String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(passWordNew1, ""));// 加密
					User userNew=new User();
					userNew.setId(user.getId());
					userNew.setPassword(checkPassWord);// 新密码
					int count = userService.updateByPrimaryKeyUser(userNew);
					if (count > 0) {
						code = "0";
						msg = "修改成功";
						flage = "true";

						loginSucc(request, userNew);
					} else {
						code = "-1";
						msg = "修改失败";
						return;
					}
				} else {
					code = "-1";
					msg = "原密码错误";
					return;

				}
			} else {
				code = "-2";
				msg = "请先登录";
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(EDIT_PASSWD_CHECK, deviceId);
			resultMap.put("item", flage);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", resultMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 修改密码 验证码是否通过
	 */
	@RequestMapping("credit-user/verify-reset-password")
	public void loginForgotUpdatePassWordOne(HttpServletRequest request, HttpServletResponse response) {
		String appVersion = request.getParameter("appVersion");
		String[] str = appVersion.split("\\.");
		String v = "";
		if (str[0].toLowerCase().indexOf("V")!=-1) {
			v = str[0].substring(1, str[0].length()-1);
		}else{
			v = str[0];
		}
		int v2 = Integer.parseInt(v+str[1]+str[2]);
		if (v2>=220) {
			JSONObject json = new JSONObject();
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			Map<String, Object> param = getParametersO(request);
			HashMap<String, Object> map = new HashMap<String, Object>();

			String code = "-1";
			String msg = "";
			String item = "";
			try {
				String userPhone = request.getParameter("phone");// 手机号码
				String smsCode = request.getParameter("code");// 验证码
				map.put("userPhone", userPhone);
				User user = this.userService.searchUserByCheckTel(map);// 根据手机号查询
				if (user != null) {
					if (param.containsKey("type") && param.get("type").equals("find_pwd")) {// 登录密码找回
						String deviceId = request.getParameter("deviceId");
						String errorCount = jedisCluster.get(BACK_PASS_COUNT+deviceId); //获取redis用户注册验证码输错次数
						if (StringUtils.isNotBlank(errorCount) && Integer.parseInt(errorCount) >= 3) {
							if (!validateSubmitAPP(request, response)) {
								msg = "图形验证码错误";
								return;
							}
						}
						String sendSmsCode = jedisCluster.get(SMS_FIND_PREFIX + userPhone);
						if ("".equals(smsCode)) {
							msg = "验证码不能为空";
						} else if (StringUtils.isBlank(sendSmsCode)) {
							msg = "验证码已失效，请重新获取";
						} else if (!sendSmsCode.equals(smsCode)) {
							msg = "验证码不正确";
						} else if (sendSmsCode.equals(smsCode)) {
							jedisCluster.del(BACK_PASS_COUNT+deviceId); //清空图形验证码输错次数
							code = "0";
							msg = "成功找回密码";
							item = "1";
							resultMap.put("item", item);
						}
					} else if (param.containsKey("type") && param.get("type").equals("find_pay_pwd")) {// 交易密码找回

						String sendSmsCode = jedisCluster.get(SMS_TRADE_FIND_PREFIX + userPhone);

						String name = param.get("realname") + "";// 真实姓名
						String id_number = param.get("id_card") + "";// 身份证号码

						if (user.getRealname().equals(name)) {
							if (user.getIdNumber().equals(id_number)) {
								if (StringUtils.isBlank(sendSmsCode)) {
									msg = "验证码已失效，请重新获取";
								} else if ("".equals(smsCode)) {
									msg = "验证码不能为空";
								} else if (!sendSmsCode.equals(smsCode)) {
									msg = "验证码不正确";
								} else if (sendSmsCode.equals(smsCode)) {
									code = "0";
									msg = "成功找回密码";
									item = "1";
									resultMap.put("item", item);
									resultMap.put("code", smsCode);
								}
							} else {
								code = "-1";
								msg = "身份证号码不正确";
							}
						} else {
							code = "-1";
							msg = "真实姓名不正确";
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				code = "500";
				msg = "系统异常";
			} finally {
				json.put("code", code);
				json.put("message", msg);
				json.put("data", resultMap);
				JSONUtil.toObjectJson(response, json.toString());
			}
		}else{
			loginForgotUpdatePassWordOneV211(request, response);
		}
	}
	
	/**
	 * 修改密码 验证码是否通过,没有版本管理该方法在2.2.0版本之前用
	 * @param request
	 * @param GENERATE_REGISTER_CODE_CHECK
	 * @param response
	 */
	private void loginForgotUpdatePassWordOneV211(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> param = getParametersO(request);
		HashMap<String, Object> map = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";
		String item = "";
		try {
			String userPhone = request.getParameter("phone");// 手机号码
			String smsCode = request.getParameter("code");// 验证码
			map.put("userPhone", userPhone);
			User user = this.userService.searchUserByCheckTel(map);// 根据手机号查询
			if (user != null) {
				if (param.containsKey("type") && param.get("type").equals("find_pwd")) {// 登录密码找回
					String sendSmsCode = jedisCluster.get(SMS_FIND_PREFIX + userPhone);
					if ("".equals(smsCode)) {
						msg = "验证码不能为空";
					} else if (StringUtils.isBlank(sendSmsCode)) {
						msg = "验证码已失效，请重新获取";
					} else if (!sendSmsCode.equals(smsCode)) {
						msg = "验证码不正确";
					} else if (sendSmsCode.equals(smsCode)) {
						code = "0";
						msg = "成功找回密码";
						item = "1";
						resultMap.put("item", item);
					}
				} else if (param.containsKey("type") && param.get("type").equals("find_pay_pwd")) {// 交易密码找回

					String sendSmsCode = jedisCluster.get(SMS_TRADE_FIND_PREFIX + userPhone);

					String name = param.get("realname") + "";// 真实姓名
					String id_number = param.get("id_card") + "";// 身份证号码

					if (user.getRealname().equals(name)) {
						if (user.getIdNumber().equals(id_number)) {
							if (StringUtils.isBlank(sendSmsCode)) {
								msg = "验证码已失效，请重新获取";
							} else if ("".equals(smsCode)) {
								msg = "验证码不能为空";
							} else if (!sendSmsCode.equals(smsCode)) {
								msg = "验证码不正确";
							} else if (sendSmsCode.equals(smsCode)) {
								code = "0";
								msg = "成功找回密码";
								item = "1";
								resultMap.put("item", item);
								resultMap.put("code", smsCode);
							}
						} else {
							code = "-1";
							msg = "身份证号码不正确";
						}
					} else {
						code = "-1";
						msg = "真实姓名不正确";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			json.put("code", code);
			json.put("message", msg);
			json.put("data", resultMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 忘记修改密码第二步 提交
	 */
	@RequestMapping("credit-user/reset-password")
	public void loginForgotUpdatePassWordtWO(HttpServletRequest request, HttpServletResponse response) {
		String RESET_PASSWD_CHECK = "rest_passwd_check_";

		JSONObject json = new JSONObject();
		Map<String, Map<String, Object>> dataMap = new HashMap<String, Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";
		String item = "0";
		AESUtil desEncrpt = new AESUtil();
		AESUtil aesEncrypt = new AESUtil();
		String userPhone = "";
		try {
			// 未登录
			userPhone = request.getParameter("phone");// 手机号码
			String passWordNew = request.getParameter("password");// 新密码
			if (StringUtils.isBlank(userPhone)) {
				code = "-1";
				msg = "手机号码不能为空";
				return;
			}
		    Long remainTime=checkForFront(RESET_PASSWD_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			if (StringUtils.isBlank(passWordNew)) {
				code = "-1";
				msg = "请输入新密码";
				return;
			}
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("userPhone", userPhone);
			User user = this.userService.searchUserByCheckTel(map);
			if (user != null) {
				String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(passWordNew, ""));// 加密
				User userNew=new User();
				userNew.setId(user.getId());
				userNew.setPassword(checkPassWord);// 新密码
				
				int count = userService.updateByPrimaryKeyUser(userNew);
				if (count > 0) {
					code = "0";
					msg = "设置成功";
					item = "1";
					loginSucc(request, userNew);
				} else {
					code = "-1";
					msg = "设置失败";
				}
			} else {
				code = "-1";
				msg = "手机号码不存在";
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(RESET_PASSWD_CHECK, userPhone);
			resultMap.put("item", item);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", resultMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 设置交易密码
	 */
	@RequestMapping("credit-user/set-paypassword")
	public void saveUpdatePaypassword(HttpServletRequest request, HttpServletResponse response) {
		String RESET_PAY_PASSWD_CHECK = "rest_pay_passwd_check_";
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";

		AESUtil desEncrpt = new AESUtil();
		AESUtil aesEncrypt = new AESUtil();
		String deviceId = request.getParameter("deviceId");
		try {
		    Long remainTime=checkForFront(RESET_PAY_PASSWD_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				if (user.getRealnameStatus().equals("1")) {// 实名已认证
					String payPassword = request.getParameter("password");// 交易密码
					if (!payPassword.equals("")) {
						String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(payPassword, ""));// 加密
						User userNew=new User();
						userNew.setId(user.getId());
						userNew.setPayPassword(checkPassWord);// 新密码
						int count = userService.updateByPrimaryKeyUser(userNew);
						if (count > 0) {
							code = "0";
							msg = "成功保存交易密码";
							resultMap.put("true", true);
							loginSucc(request, userNew);
						} else {
							code = "-1";
							msg = "保存交易密码失败";
							resultMap.put("false", false);
						}
					} else {
						code = "-1";
						msg = "请输入交易密码";
					}
				} else {
					code = "-1";
					msg = "请先完善个人信息";
				}
			} else {
				code =Status.LOGIN.getName();
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(RESET_PAY_PASSWD_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 登录时 修改交易密码
	 */
	@RequestMapping("credit-user/change-paypassword")
	public void loginUpdatePaypassword(HttpServletRequest request, HttpServletResponse response) {
		String CHANGE_PAY_PASSWD = "change_pay_passwd_";
		JSONObject json = new JSONObject();
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";

		AESUtil desEncrpt = new AESUtil();
		AESUtil aesEncrypt = new AESUtil();
		String deviceId = request.getParameter("deviceId");
		try {
		    Long remainTime=checkForFront(CHANGE_PAY_PASSWD, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				String passWordOld1 = request.getParameter("old_pwd");// 原密码
				String passWordNew1 = request.getParameter("new_pwd");// 新密码
				String checkPassWordOld = MD5coding.MD5(aesEncrypt.encrypt(passWordOld1, ""));// 加密

				if (user.getPayPassword().equals(checkPassWordOld)) {// 判断输入的密码是否与原密码一致
					String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(passWordNew1, ""));// 加密
					User userNew=new User();
					userNew.setId(user.getId());
					userNew.setPayPassword(checkPassWord);// 新密码
					int count = userService.updateByPrimaryKeyUser(userNew);
					if (count > 0) {
						code = "0";
						msg = "修改交易密码成功";
						resultMap.put("true", true);
						loginSucc(request,userNew);
					} else {
						code = "-1";
						msg = "修改交易密码失败";
						resultMap.put("false", false);
					}
				} else {
					code = "-1";
					msg = "原密码错误";
				}
			} else {
				code =Status.LOGIN.getName();
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(CHANGE_PAY_PASSWD, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 忘记交易密码 第二步 提交
	 */
	@RequestMapping("credit-user/reset-pay-password")
	public void loginForgotUpdatePaypasswordTwo(HttpServletRequest request, HttpServletResponse response) {
		String RESET_PAY_PASSWD_SECOND_CHECK = "reset_pay_passwd_second_check_";
		JSONObject json = new JSONObject();
		Map<String, Map<String, Object>> dataMap = new HashMap<String, Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String code = "-1";
		String msg = "";
		String item = "0";
		AESUtil desEncrpt = new AESUtil();
		AESUtil aesEncrypt = new AESUtil();
		String deviceId = request.getParameter("deviceId");
		try {
		    Long remainTime=checkForFront(RESET_PAY_PASSWD_SECOND_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			// 未登录
			String userPhone = request.getParameter("phone");// 手机号码
			String passWordNew = request.getParameter("password");// 新交易密码
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("userPhone", userPhone);
			User user = this.userService.searchUserByCheckTel(map);// 用户是否存在
			if (user != null) {
				String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(passWordNew, ""));// 加密
				User userNew=new User();
				userNew.setId(user.getId());
				userNew.setPayPassword(checkPassWord);// 新交易密码
				int count = userService.updateByPrimaryKeyUser(userNew);
				if (count > 0) {
					code = "0";
					msg = "设置成功";
					item = "1";
					loginSucc(request, userNew);
				} else {
					code = "-1";
					msg = "设置失败";
				}
			} else {
				code = "-1";
				msg = "手机号码不存在";
				return;
			}

		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(RESET_PAY_PASSWD_SECOND_CHECK, deviceId);
			resultMap.put("item", item);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", resultMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 退出
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("credit-user/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) {

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		String code = "-1";
		String msg = "";
		try {
			loginOut(request);
			code = "0";
			msg = "成功退出";
			resultMap.put("true", true);
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			dataMap.put("result", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 获取认证列表中--》获取个人信息
	 */
	@RequestMapping("credit-card/get-person-info")
	public void getPersonInfo(HttpServletRequest request, HttpServletResponse response) {
		loger.info("credit-card/get-person-info start");
		long startTime = System.currentTimeMillis();
		String GET_PERSON_INFO_CHECK = "get_person_info_check_";

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		List<Map<String, String>> degrees_all = new ArrayList<Map<String, String>>();
		List<Map<String, String>> marriage_all = new ArrayList<Map<String, String>>();
		List<Map<String, String>> live_time_type_all = new ArrayList<Map<String, String>>();

		String code = "-1";
		String msg = "";
		String deviceId = request.getParameter("deviceId");
		try {
			code = "0";
			msg = "成功获取身份信息";
			User logUser = this.loginFrontUserByDeiceId(request);

			if (logUser != null) {
				loger.info("credit-card/get-person-info logUser userId:" + logUser.getId());

				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));

				String name = StringUtils.isNotBlank(user.getRealname()) ? user.getRealname() : "";
				String id_number = StringUtils.isNotBlank(user.getIdNumber()) ? user.getIdNumber() : "";
				String address = StringUtils.isNotBlank(user.getPresentAddress()) ? user.getPresentAddress() : "";
				String live_period = StringUtils.isNotBlank(user.getPresentPeriod()) ? user.getPresentPeriod() : "";
				String address_distinct = StringUtils.isNotBlank(user.getPresentAddressDistinct()) ? user.getPresentAddressDistinct() : "";
				String longitude = StringUtils.isNotBlank(user.getPresentLongitude()) ? user.getPresentLongitude() : "";
				String latitude = StringUtils.isNotBlank(user.getPresentLatitude()) ? user.getPresentLatitude() : "";
				String face_recognition_picture =  "";
				String id_number_z_picture = "";
				String id_number_f_picture = "";
				if(StringUtils.isNotBlank(user.getHeadPortrait())){
					face_recognition_picture = Constant.HTTP + domainOfBucket + "/" + user.getHeadPortrait();
				}
				if(StringUtils.isNotBlank(user.getIdcardImgZ())){
					id_number_z_picture = Constant.HTTP + domainOfBucket + "/" + user.getIdcardImgZ();
				}
				if(StringUtils.isNotBlank(user.getIdcardImgF())){
					id_number_f_picture = Constant.HTTP + domainOfBucket + "/" + user.getIdcardImgF();
				}
				String degrees = StringUtils.isNotBlank(user.getEducation()) ? user.getEducation() : "";
				String marriage = StringUtils.isNotBlank(user.getMaritalStatus()) ? user.getMaritalStatus() : "";

				for (Entry<String, String> entry : User.EDUCATION_TYPE.entrySet()) {// 学历
					Map<String, String> map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("degrees", entry.getKey());
					map.put("name", entry.getValue());
					degrees_all.add(map);
					resultMap.put("degrees_all", degrees_all);
				}
				for (Entry<String, String> entry : User.MARRIAGE_STATUS.entrySet()) {// 婚姻状况
					Map<String, String> map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("marriage", entry.getKey());
					map.put("name", entry.getValue());
					marriage_all.add(map);
					resultMap.put("marriage_all", marriage_all);
				}
				for (Entry<String, String> entry : User.RESIDENCE_DATE.entrySet()) {// 居住时长
					Map<String, String> map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("live_time_type", entry.getKey());
					map.put("name", entry.getValue());
					live_time_type_all.add(map);
					resultMap.put("live_time_type_all", live_time_type_all);
				}
				resultMap.put("id", user.getId());// ID
				resultMap.put("name", name);// 真实姓名
				resultMap.put("id_number", id_number);// 身份证号码
				resultMap.put("degrees", degrees);// 学历
				resultMap.put("marriage", marriage);// 婚姻状况
				resultMap.put("address", address);// 居住地址
				resultMap.put("live_period", live_period);// 居住时长
				resultMap.put("address_distinct", address_distinct);// 居住详细地址
				resultMap.put("longitude", longitude);// 纬度
				resultMap.put("latitude", latitude);// 经度
				resultMap.put("real_verify_status", user.getRealnameStatus());// 实名认证状态
				resultMap.put("face_recognition_picture", face_recognition_picture);// 头像
				resultMap.put("id_number_z_picture", id_number_z_picture);// 身份证正面
				resultMap.put("id_number_f_picture", id_number_f_picture);// 身份证反面

				loger.info("credit-card/get-person-info logUser userId:" + logUser.getId() + ",resultMap:" + resultMap);
			} else {
				code = "-2";
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_PERSON_INFO_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
			loger.info("credit-card/get-person-info end,cost:" + (System.currentTimeMillis() - startTime) / 1000 + "s");
		}
	}

	/**
	 * 获取认证列表中--》未实名认证 保存个人信息
	 */
	@RequestMapping("credit-card/get-person-infos")
	public void getPersonInfos(HttpServletRequest request, HttpServletResponse response) {
		String GET_PERSON_INFOS_CHECK = "get_person_infos_check_";
		loger.info("credit-card/get-person-infos start");
		long startTime = System.currentTimeMillis();

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		String code = "-1";
		String msg = "";
		String deviceId = request.getParameter("deviceId");
		try {
		    Long remainTime=checkForFront(GET_PERSON_INFOS_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);

			if (logUser != null) {
				loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId());
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));

				User usr = new User();
				String name = request.getParameter("name");// 姓名
				String idNumber = request.getParameter("id_number");// 身份证号码
				String status = request.getParameter("real_verify_status");// 认证状态
				String education = request.getParameter("degrees");// 学历
				String address = request.getParameter("address");// 地址
				String addressDistinct = request.getParameter("address_distinct");// 详细地址
				String liveTime = request.getParameter("live_time_type");// 居住时长
				String longitude = request.getParameter("longitude");// 纬度
				String latitude = request.getParameter("latitude");// 经度
				String headPortrait = request.getParameter("face_recognition_picture");// 人脸识别
				String marriage = request.getParameter("marriage");// 婚姻状况
				Map<String, String> params = new HashMap<String, String>();

				loger.info("getPersonInfos headPortrait:" + headPortrait + ",name:" + name + ",idNumber:" + idNumber);

				if (StringUtils.isBlank(user.getHeadPortrait()) || StringUtils.isBlank(user.getIdcardImgZ()) || StringUtils.isBlank(user.getIdcardImgF())) {
					loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",required ID card peicture is null");
					code = "-1";
					msg = "请先上传头像和身份证正反面";
					return;
				}

				if (StringUtils.isBlank(name) || StringUtils.isBlank(idNumber)) {
					loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",required name or idNumber is null");
					code = "-1";
					msg = "请输入完整的信息";
					return;
				}
				
				if (StringUtils.isNotBlank(education) && "8".equals(education)) {
					loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",education == 8");
					code = "-1";
					msg = "请先选择学历";
					return;
				}

				//String realPath = request.getSession().getServletContext().getRealPath("");
				params.put("idcard_name", name);
				params.put("idcard_number", idNumber);
				params.put("faceImageAttach", domainOfBucket + "/" + user.getHeadPortrait());
				params.put("userId", user.getId());
				String api_key = getAppConfig(request.getParameter("appName"), "XJX_API_KEY");
				String api_secret = getAppConfig(request.getParameter("appName"), "XJX_API_SECRET");
				JsonResult result = httpCertification.face(user, params, api_key, api_secret);
				//TODO songss 模拟访问人脸api成功
				loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",result:" + result);

				if (!result.isSuccessed()) {
					loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",result successed is false");
					code = "-1";
					msg =result.getMsg();
					return;
				}

				usr.setRealnameStatus("1");// 已认证
				usr.setRealnameTime(new Date());// 实名认证时间

				Integer birthDay = Integer.valueOf(idNumber.substring(6, 10));
				usr.setUserAge(Calendar.getInstance().get(Calendar.YEAR) - birthDay);// 年龄
				usr.setId(user.getId());
				usr.setRealname(name);
				usr.setIdNumber(idNumber);
				usr.setPresentAddress(address);
				usr.setPresentPeriod(liveTime);// 居住时长
				usr.setEducation(education);
				usr.setPresentLongitude(longitude);
				usr.setPresentLatitude(latitude);
				usr.setMaritalStatus(marriage);
				usr.setPresentAddressDistinct(addressDistinct);
				int count = this.userService.updateByPrimaryKeyUser(usr);

				if (count <= 0) {
					loger.info("credit-card/get-person-infos logUser userId:" + logUser.getId() + ",update count < 0,update fail");
					code = "-1";
					msg = "保存失败";
					return;
				}

				code = "0";
				msg = "成功保存身份信息";
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userId", Integer.parseInt(usr.getId()));
				this.infoIndexService.authInfo(map);// 初始设置
				
				//TODO songss 地推推送是否要注释掉
				//地推 实名认证
				HashMap<String, Object> maps = new HashMap<String, Object>();
				maps.put("realName", usr.getRealname());
    			ThreadPool pool = ThreadPool.getInstance();
    			pool.execute(new DtThread(UserPushUntil.REALNAME, Integer.parseInt(usr.getId()), null, new Date(), userService,
    					pushUserService, null,maps));
    			
				User userNow = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				loginSucc(request, userNow);

			} else {
				code = "-2";
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_PERSON_INFOS_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
			loger.info("credit-card/getPersonInfos end,cost:" + (System.currentTimeMillis() - startTime) / 1000 + "s");
		}
	}

	/**
	 * 获取认证列表中--》已经名认证 保存个人信息
	 */
	@RequestMapping("credit-info/save-person-info")
	public void savePersonInfos(HttpServletRequest request, HttpServletResponse response) {
		String SAVE_PERSON_INFO_CHECK = "save_person_info_check_";
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		String deviceId = request.getParameter("deviceId");
		String code = "-1";
		String msg = "";
		try {
		    Long remainTime=checkForFront(SAVE_PERSON_INFO_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				// User usr=new User();
				String education = request.getParameter("degrees");// 学历
				String address = request.getParameter("address");// 地址
				String addressDistinct = request.getParameter("address_distinct");// 详细地址
				String liveTime = request.getParameter("live_time_type");// 居住时长
				String longitude = request.getParameter("longitude");// 纬度
				String latitude = request.getParameter("latitude");// 经度
				String marriage = request.getParameter("marriage");// 婚姻状况

				if (StringUtils.isNotBlank(education) && "8".equals(education)) {
					loger.info("credit-info/save-person-info logUser userId:" + logUser.getId() + ",education == 8");
					code = "-1";
					msg = "请先选择学历";
					return;
				}
				
				User userNew=new User();
				userNew.setId(user.getId());
				// user.setId(user.getId());
				userNew.setPresentAddress(address);
				userNew.setPresentPeriod(liveTime);// 居住时长
				userNew.setEducation(education);
				userNew.setPresentLongitude(longitude);
				userNew.setPresentLatitude(latitude);
				userNew.setMaritalStatus(marriage);
				userNew.setPresentAddressDistinct(addressDistinct);
				int count = this.userService.updateByPrimaryKeyUser(userNew);
				if (count > 0) {
					code = "0";
					msg = "成功保存身份信息";
					loginSucc(request, userNew);
				} else {
					code = "-1";
					msg = "保存失败";
				}
			} else {
				code = "-2";
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(SAVE_PERSON_INFO_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 获取认证列表中--》紧急联系人
	 */
	@RequestMapping("credit-card/get-contacts")
	public void getContacts(HttpServletRequest request, HttpServletResponse response) {
		String GET_CONTACTS_CHECK = "get_contact_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		List lineal_list = new ArrayList();
		List other_list = new ArrayList();

		String code = "-1";
		String msg = "";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				code = "0";
				msg = "成功获取紧急联系人";

				for (Entry<String, String> entry : User.CONTACTS_FAMILY.entrySet()) {// 直系亲属联系人
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("type", entry.getKey());
					map.put("name", entry.getValue());
					lineal_list.add(map);
					resultMap.put("lineal_list", lineal_list);
				}

				for (Entry<String, String> entry : User.CONTACTS_OTHER.entrySet()) {// 其他联系人
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("type", entry.getKey());
					map.put("name", entry.getValue());
					other_list.add(map);
					resultMap.put("other_list", other_list);
				}
				String lineal_relation = "";
				if (user.getFristContactRelation() != null) {
					lineal_relation = user.getFristContactRelation();
				}
				String lineal_name = "";
				if (user.getFirstContactName() != null) {
					lineal_name = user.getFirstContactName();
				}
				String lineal_mobile = "";
				if (user.getFirstContactPhone() != null) {
					lineal_mobile = user.getFirstContactPhone();
				}
				String other_relation = "";
				if (user.getSecondContactRelation() != null) {
					other_relation = user.getSecondContactRelation();
				}
				String other_name = "";
				if (user.getSecondContactName() != null) {
					other_name = user.getSecondContactName();
				}
				String other_mobile = "";
				if (user.getSecondContactPhone() != null) {
					other_mobile = user.getSecondContactPhone();
				}

				resultMap.put("lineal_relation", lineal_relation);// 直系亲属
				resultMap.put("lineal_name", lineal_name);// 直系亲属称呼
				resultMap.put("lineal_mobile", lineal_mobile);// 直系亲属电话
				resultMap.put("other_relation", other_relation);// 其他联系
				resultMap.put("other_name", other_name);// 其他联系称呼
				resultMap.put("other_mobile", other_mobile);// 其他联系电话
			} else {
				code =Status.LOGIN.getName();
				msg = "请先登录";
			}

		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_CONTACTS_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	public String handleMoblile(String mobile) {
		mobile = mobile.trim();
		Pattern pattern = Pattern.compile("^1\\d{10}$");
		if (mobile.startsWith("86")) {
			mobile = mobile.substring(2, mobile.length());
		} else if (mobile.startsWith("+86")) {
			mobile = mobile.substring(3, mobile.length());
		}
		// System.out.println(mobile);
		Matcher linealMobileMaths = pattern.matcher(mobile);
		if (linealMobileMaths.matches()) {
			return mobile;
		} else {
			return "";
		}

	}

	/**
	 * 获取认证列表中--》保存紧急联系人
	 */
	@RequestMapping("credit-card/get-contactss")
	public void getContactss(HttpServletRequest request, HttpServletResponse response) {
		String GET_CONTACTSSS_CHECK = "get_contacts_check_";
		String deviceId = request.getParameter("deviceId");

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		List lineal_list = new ArrayList();
		List other_list = new ArrayList();

		String code = "-1";
		String msg = "";
		try {
		    Long remainTime=checkForFront(GET_CONTACTSSS_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				if(!"2".equals(user.getJxlStatus())){
					String linealRelation = request.getParameter("type");// 直系联系人标识
					String linealName = request.getParameter("name");// 直系联系人
					String linealMobile = request.getParameter("mobile");// 直系联系人电话
					String otherRelation = request.getParameter("relation_spare");// 其他联系人标识
					String otherName = request.getParameter("name_spare");// 其他联系人
					String otherMobile = request.getParameter("mobile_spare");// 其他联系人电话

					// 用户表
					// User usr=new User();
					// usr.setId(user.getId());
					User userNew=new User();
					userNew.setId(user.getId());
					// 直系联系人
					userNew.setFristContactRelation(linealRelation);
					Pattern p = Pattern.compile("[\\u4e00-\\u9fa5][\\u4e00-\\u9fa5\\·]{0,40}[\\u4e00-\\u9fa5]|[\\u4e00-\\u9fa5]"); // 正则
					Matcher m = p.matcher(linealName);
					if (m.matches()) { // 当联系人名称为汉字时入库
						userNew.setFirstContactName(linealName);
					} else {
						code = "-1";
						msg = "直接联系人名称有误";
						return;
					}

					loger.info("linealMobile:" + linealMobile);

					if (StringUtils.isNotBlank(linealMobile)) {
						if (linealMobile.contains(":")) {
							String[] mobleArray = linealMobile.split(":");
							if (null != mobleArray && 0 < mobleArray.length) {
								for (String oneMobile : mobleArray) {
									if (StringUtils.isNotBlank(oneMobile)) {
										String contacMobile = handleMoblile(oneMobile);
										if (StringUtils.isNotBlank(contacMobile)) {
											if(contacMobile.length()!=11){
												code="-1";
												msg="直接联系人手机号码格式不正确";
												return ;
											}
											userNew.setFirstContactPhone(contacMobile);
											break;
										}

									}
								}
							}
						} else {
							String contactMobile = handleMoblile(linealMobile);
							if(contactMobile.length()!=11){
								code="-1";
								msg="直接联系人手机号码格式不正确";
								return ;
							}
							userNew.setFirstContactPhone(contactMobile);
						}

						if (StringUtils.isBlank(userNew.getFirstContactPhone())) {
							code = "-1";
							msg = "紧急直接联系人为空";
							return;
						}

					} else {
						code = "-1";
						msg = "紧急直接联系人参数为空";
						return;
					}

					// 其他联系人
					userNew.setSecondContactRelation(otherRelation);
					Matcher mm = p.matcher(otherName);
					if (mm.matches()) { // 当联系人名称为汉字时入库
						userNew.setSecondContactName(otherName);
					} else {
						code = "-1";
						msg = "其他联系人名称有误";
						return;
					}
					// 00000000000000000000000000000000000000000000000000000

					loger.info("otherMobile:" + otherMobile);

					if (StringUtils.isNotBlank(otherMobile)) {
						if (otherMobile.contains(":")) {
							String[] mobleArray = otherMobile.split(":");
							if (null != mobleArray && 0 < mobleArray.length) {
								for (String oneMobile : mobleArray) {
									if (StringUtils.isNotBlank(oneMobile)) {
										String contacMobile = handleMoblile(oneMobile);
										if (StringUtils.isNotBlank(contacMobile)) {
											if(contacMobile.length()!=11){
												code="-1";
												msg="紧急直接联系人手机号码格式不正确";
												return ;
											}
											userNew.setSecondContactPhone(contacMobile);
											break;
										}
									}
								}
							}
						} else {
							String contactMobile = handleMoblile(otherMobile);
							if(contactMobile.length()!=11){
								code="-1";
								msg="紧急直接联系人手机号码格式不正确";
								return ;
							}
							userNew.setSecondContactPhone(contactMobile);
						}

						if (StringUtils.isBlank(userNew.getSecondContactPhone())) {
							code = "-1";
							msg = "紧急其他联系人为空";
							return;
						}
					} else {
						code = "-1";
						msg = "紧急其他联系人参数为空";
						return;
					}

					// 00000000000000000000000000000000000000000000000000000
					loger.info("firstContactPhone:" + userNew.getFirstContactPhone() + ",SecondContactPhone:" + userNew.getSecondContactPhone());

					HashMap<String, Object> contactMap = new HashMap<String, Object>();
					contactMap.put("userId", userNew.getId());// 用户ID

					int count = this.userService.updateByPrimaryKeyUser(userNew);
					if (count > 0) {
						code = "0";
						msg = "成功保存紧急联系人";
						loginSucc(request, userNew);

						HashMap<String, Object> cmap = new HashMap<String, Object>();
						cmap.put("userId", Integer.parseInt(userNew.getId()));
						this.infoIndexService.authContacts(cmap);// 设置状态
						
				       	//地推 紧急联系人认证
	        			ThreadPool pool = ThreadPool.getInstance();
	        			pool.execute(new DtThread(UserPushUntil.CONTACTAPPROVE, Integer.valueOf(user.getId()), null, new Date(), userService,
	        					pushUserService, null,null));

						for (Entry<String, String> entry : User.WORK_DATE.entrySet()) {// 直系亲属联系人
							Map map = new HashMap<String, String>();
//							System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
							map.put("type", entry.getKey());
							map.put("name", entry.getValue());
							lineal_list.add(map);
							resultMap.put("lineal_list", lineal_list);
						}

						for (Entry<String, String> entry : User.CONTACTS_OTHER.entrySet()) {// 其他联系人
							Map map = new HashMap<String, String>();
//							System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
							map.put("type", entry.getKey());
							map.put("name", entry.getValue());
							other_list.add(map);
							resultMap.put("other_list", other_list);
						}

						resultMap.put("lineal_relation", linealRelation);
						resultMap.put("lineal_name", linealName);
						resultMap.put("lineal_mobile", linealMobile);
						resultMap.put("other_relation", otherRelation);
						resultMap.put("other_name", otherName);
						resultMap.put("other_mobile", otherMobile);
					} else {
						code = "-1";
						msg = "保存紧急联系人失败";
					}
				}else{
					code = "-1";
					msg = "您的紧急联系人已通过认证不能再修改";
				}
			} else {
				code =Status.LOGIN.getName();
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_CONTACTSSS_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 获取认证列表中--》获取工作详细信息
	 */
	@RequestMapping("credit-card/get-work-info")
	public void getWorkInfo(HttpServletRequest request, HttpServletResponse response) {
		String GET_WORK_INFO_CHECK = "get_work_info_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		List company_period_list = new ArrayList();
		List company_worktype_list = new ArrayList();

		String code = "-1";
		String msg = "";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				code = "0";
				msg = "成功获取工作信息";
				for (Entry<String, String> entry : User.WORK_DATE.entrySet()) {// 工作时长
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("entry_time_type", entry.getKey());
					map.put("name", entry.getValue());
					company_period_list.add(map);
					resultMap.put("company_period_list", company_period_list);
				}

				for (Entry<String, String> entry : User.WORK_TYPE.entrySet()) {// 工作类型
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("work_type_id", entry.getKey());
					map.put("name", entry.getValue());
					company_worktype_list.add(map);
					resultMap.put("company_worktype_list", company_worktype_list);
				}

				String company_name = "";
				if (user.getCompanyName() != null) {
					company_name = user.getCompanyName();
				}
				String company_address = "";
				if (user.getCompanyAddress() != null) {
					company_address = user.getCompanyAddress();
				}
				String company_longitude = "";
				if (user.getCompanyLongitude() != null) {
					company_longitude = user.getCompanyLongitude();
				}
				String company_latitude = "";
				if (user.getCompanyLatitude() != null) {
					company_latitude = user.getCompanyLatitude();
				}
				String company_address_distinct = "";
				if (user.getCompanyAddressDistinct() != null) {
					company_address_distinct = user.getCompanyAddressDistinct();
				}
				String company_phone = "";
				if (user.getCompanyPhone() != null) {
					company_phone = user.getCompanyPhone();
				}
				String company_period = "";
				if (user.getCompanyPeriod() != null) {
					company_period = user.getCompanyPeriod();
				}
				// String company_worktype="";
				// if(user.getCompanyPeriod()!=null){
				// company_worktype=user.getCompanyName();
				// }
				resultMap.put("company_name", company_name);// 公司名称
				// resultMap.put("company_post",company_post);//
				resultMap.put("company_address", company_address);// 工作地址
				resultMap.put("company_longitude", company_longitude);// 经度
				resultMap.put("company_latitude", company_latitude);// 纬度
				resultMap.put("company_address_distinct", company_address_distinct);// 详细地址
				resultMap.put("company_phone", company_phone);// 公司电话
				resultMap.put("company_period", company_period);// 工作时长
				List<UserInfoImage> userInfoImage = this.userInfoImageService.selectImageByUserId(Integer.parseInt(user.getId()));
				String company_picture = "0";
				if (userInfoImage != null && userInfoImage.size() > 0) {
					company_picture = "1";
				}

				resultMap.put("company_picture", company_picture);// 是否有工作照
				// resultMap.put("company_worktype_id",);//工作类型
				// resultMap.put("company_worktype",User.WORK_TYPE.get(company_worktype));//工作类型
			} else {
				code = "-1";
				msg = "失败";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_WORK_INFO_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 获取认证列表中--》保存工作详细信息
	 */
	@RequestMapping("credit-card/save-work-info")
	public void saveWorkInfo(HttpServletRequest request, HttpServletResponse response) {
		String SAVE_WORK_INFO_CHECK = "save_work_info_check_";
		String deviceId = request.getParameter("deviceId");

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		List company_period_list = new ArrayList();
		List company_worktype_list = new ArrayList();

		String code = "-1";
		String msg = "";
		try {
			Long remainTime=checkForFront(SAVE_WORK_INFO_CHECK, deviceId);
			if (remainTime>0) {
				code=Status.FREQUENT.getName();
				json.put("time", remainTime);
				msg = Status.FREQUENT.getValue();
				return;
			}
			String companyPhone = request.getParameter("company_phone");// 单位电话
			if (null != companyPhone && companyPhone.length() != 0) {
				if (!companyPhone.contains("-")) {
					code = "-1";
					msg = "请输入完整的单位号码（包含区号和横杠分隔符），例如：021-xxxxxxxx";
					return;
				}
			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				String companyName = request.getParameter("company_name");// 单位名称
				String companyAddress = request.getParameter("company_address");// 单位地址
				String companyAddressDistinct = request.getParameter("company_address_distinct");// 详细地址
				String latitude = request.getParameter("latitude");// 纬度
				String longitude = request.getParameter("longitude");// 经度
				String companyPicture = request.getParameter("company_picture");// 是否有工作证照
				String companyPeriod = request.getParameter("company_period");// 工作时长

				 User userNew=new User();
				 userNew.setId(user.getId());
				 userNew.setCompanyName(companyName);
				 userNew.setCompanyPhone(companyPhone);
				 userNew.setCompanyAddress(companyAddress);
				 userNew.setCompanyAddressDistinct(companyAddressDistinct);
				 userNew.setCompanyPeriod(companyPeriod);

				int count = this.userService.updateByPrimaryKeyUser(userNew);
				if (count > 0) {
					code = "0";
					msg = "成功保存工作信息";
					loginSucc(request, userNew);
					
					//地推 工作信息
	    			ThreadPool pool = ThreadPool.getInstance();
	    			pool.execute(new DtThread(UserPushUntil.COMPANYAPPROVE, Integer.parseInt(user.getId()), null, new Date(), userService,
	    					pushUserService, null,null));
					
				} else {
					code = "-1";
					msg = "保存工作信息失败";
				}
				resultMap.put("company_name", companyName);
				// resultMap.put("company_name", );
				resultMap.put("company_address", companyAddress);
				resultMap.put("company_longitude", longitude);
				resultMap.put("company_latitude", latitude);
				resultMap.put("company_address_distinct", companyAddressDistinct);
				resultMap.put("company_phone", companyPhone);
				resultMap.put("company_period", companyPeriod);
				String company_picture = "0";
				if (companyPicture != null) {
					company_picture = "1";
				}
				resultMap.put("company_picture", company_picture);
				for (Entry<String, String> entry : User.WORK_DATE.entrySet()) {// 工作时长
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("entry_time_type", entry.getKey());
					map.put("name", entry.getValue());
					company_period_list.add(map);
					resultMap.put("company_period_list", company_period_list);
				}

				for (Entry<String, String> entry : User.WORK_TYPE.entrySet()) {// 工作类型
					Map map = new HashMap<String, String>();
//					System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
					map.put("work_type_id", entry.getKey());
					map.put("name", entry.getValue());
					company_worktype_list.add(map);
					resultMap.put("company_worktype_list", company_worktype_list);
				}
			} else {
				code = "-2";
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(SAVE_WORK_INFO_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 获取认证列表中--》保存工作详细信息--》获取工作证件照
	 */
	@RequestMapping("picture/get-pic-list")
	public void getPicList(HttpServletRequest request, HttpServletResponse response) {
		String GET_PIC_LIST_CHECK = "get_pic_list_check_";
		String deviceId = request.getParameter("deviceId");

		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		List imgLists = new ArrayList();// 图片集合

		String code = "-1";
		String msg = "";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				List<UserInfoImage> imgList = this.userInfoImageService.selectImageByUserId(Integer.parseInt(user.getId()));
				if (imgList.size() > 0) {
					for (int i = 0; i < imgList.size(); i++) {
						Map map = (Map) imgList.get(i);
						Map redMap = new HashMap<String, Object>();
						String id = "";
						if (map.get("id") != null) {
							id = map.get("id") + "";
						}
						redMap.put("id", id);// 图片id

						String pic_name = "";
						if (map.get("id") != null) {
							pic_name = map.get("picName") + "";
						}
						redMap.put("pic_name", pic_name);// 图片名称

						String type = "";
						if (map.get("type") != null) {
							type = map.get("type") + "";
						}
						redMap.put("type", type);// 图片类型

						String url = "";
						if (map.get("url") != null) {
							//url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + map.get("url");
							url=Constant.HTTP + domainOfBucket+"/"+map.get("url");
						}
						redMap.put("url", url);// 图片路径
						imgLists.add(redMap);
					}
					code = "0";
					msg = "成功获取";
					resultMap.put("data", imgLists);
				} else {
					code = "0";
					msg = "暂无数据";
					resultMap.put("data", imgLists);
				}
			} else {
				code = "-2";
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(GET_PIC_LIST_CHECK, deviceId);
			resultMap.put("type", "6");// 图片类型
			resultMap.put("max_pictures", "3");// 存放图片 最多3张
			resultMap.put("title", "工作证照");// 工作证照
			resultMap.put("notice", "请提供可以证明您在此公司工作的照片，如含本人照片的工牌照、名片、与公司Logo合影照等");// 通知
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 意见反馈
	 */
	@RequestMapping("credit-info/feedback")
	public void feedback(HttpServletRequest request, HttpServletResponse response) {
		String FEED_BACK_CHECK = "feed_back_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();

		String code = "-1";
		String msg = "";
		try {
		    Long remainTime=checkForFront(FEED_BACK_CHECK, deviceId);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				String content = request.getParameter("content");// 反馈内容
				if (StringUtils.isBlank(content)) {
					code = "-1";
					msg = "请输入反馈内容";
					return;
				}
				String equipmentNumber = request.getParameter("deviceId");// 设备号
				PlatfromAdvise advise = new PlatfromAdvise();
				advise.setUserPhone(user.getUserPhone());// 用户手机号码
				advise.setAdviseContent(content);
				advise.setAdviseAddtime(new Date());// 当前时间
				advise.setAdviseAddip(equipmentNumber);// 反馈的设备号
				int count = this.platfromAdviseService.searchPlatfromAdvise(advise);
				if (count > 0) {
					code = "0";
					msg = "反馈成功";
					loginSucc(request, user);
				} else {
					code = "-1";
					msg = "反馈失败";
					return;
				}
			} else {
				code = "-2";
				msg = "登录已失效";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(FEED_BACK_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 关于我们
	 */
	@RequestMapping("page/detailAbout")
	public String detailAbout(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				PublicAbout about = publicAboutService.selectPublicAbout();
				if (about != null) {
					String content = about.getAboutContent()==null?"":about.getAboutContent();
					String introduce = about.getAboutIntroduce()==null?"":about.getAboutIntroduce();
					String tel = about.getAboutServiceTel()==null?"":about.getAboutServiceTel();// 公司介绍
					String qq=about.getAboutOfficialQqGroup()==null?"":about.getAboutOfficialQqGroup();//qq
					String iosCompanySwitch = getAppConfig(request.getParameter("appName"), "IOS_REALCOMPANY_TITLE_SWITCH");
					String clientType = request.getParameter("clientType");
					if("ios".equals(clientType)&&!"1".equals(iosCompanySwitch)){
						String companyTitle = getAppConfig(request.getParameter("appName"), "COMPANY_TITLE");
						String iosFakeTitle = getAppConfig(request.getParameter("appName"), "IOS_FAKECOMPANY_TITLE");
						introduce = introduce.replaceAll(companyTitle,iosFakeTitle);
					}
					model.addAttribute("content", content);//内容
					model.addAttribute("introduce", introduce);//公司介绍
					model.addAttribute("tel", tel);// 客服电话
					model.addAttribute("qq", qq);// qq群
				 }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "content/about";
	}

	/**
	 * 我的邀请
	 */
	@RequestMapping("page/detail")
	public String userInvitation(HttpServletRequest request, HttpServletResponse response) {
		return "content/invitation";
	}

	public HashMap<String, Object> createMap(String userId, String userName, String userPhone, String data) {
		List<UserContactsVo> list = JSONUtil.jsonArrayToBean(data, UserContactsVo.class);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("userName", userName);
		map.put("userPhone", userPhone);
		map.put("concatList", list);
		map.put("createTime", new Date());
		return map;
	}
	/**
	 * IOS-通讯表
	 */
	@RequestMapping("credit-info/up-load-contacts")
	public void userContacts(HttpServletRequest request, HttpServletResponse response) {
		String UP_LOAD_CONTACTS_CHECK = "up_load_contacts_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		String code = "-1";
		String msg = "";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				try {
					String data = request.getParameter("data");
					if (data != null && !"".equals(data)) {
						String userName = null;
						if (user.getRealname() != null) {
							userName=user.getRealname();
						} else {
							userName=user.getUserPhone();
						}
						User userNew=new User();
						userNew.setId(user.getId());
						userNew.setUserContactSize(userContactsService.batchInsert(createMap(user.getId(), userName, user.getUserPhone(), data))+"");// 把联系人数量入库user_info
						this.userService.updateByPrimaryKeyUser(userNew);
					}
					code = "0";
					msg = "success";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			delCheckForFront(UP_LOAD_CONTACTS_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}
	
	/**
	 * ANDROID-1.短信，2.APP，3.通讯录
	 */
	@RequestMapping("credit-info/up-load-contents")
	public void upLoadContents(HttpServletRequest request, HttpServletResponse response) {
		String UP_LOAD_CONTENTS_CHECK = "up_load_contents_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		String code = "-1";
		String msg = "失败";
		try {
			
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				String data = request.getParameter("data");
				Integer userId = Integer.parseInt(logUser.getId());

				loger.info("upLoadContents userId:" + userId);

				User user = userService.searchByUserid(userId);
				loger.info("upLoadContents,userId:"+user.getId()+",type:"+request.getParameter("type"));
				if ("1".equals(request.getParameter("type"))) {// 短信
					int count = this.obtainUserShortMessageService.selectObtainUserShortMessageCount(userId);
					if (count > 0) {// 先去库里查询用户是否有短信存在 有就删除再入库
						if (data != null && !"".equals(data)) {
							this.obtainUserShortMessageService.delObtainUserShortMessage(userId);
							JSONArray jsonArr = JSONArray.fromObject(data);
							List<ObtainUserShortMessage> shortMsgList = new ArrayList<ObtainUserShortMessage>();
							for (int i = 0; i < jsonArr.size(); i++) {
								JSONObject jsonObj = JSONObject.fromObject(jsonArr.get(i));
								ObtainUserShortMessage shortMsg = new ObtainUserShortMessage();
								shortMsg.setUserId(logUser.getId());
								shortMsg.setPhone(jsonObj.get("phone") + "");
								shortMsg.setMessageContent(UserContactsVo.setContactName(jsonObj.get("messageContent")==null?"":jsonObj.get("messageContent").toString().replaceAll("[^\u4E00-\u9FA5||0-9||a-zA-Z||\\pP]", "")));
								shortMsg.setMessageDate(jsonObj.get("messageDate") + "");

								shortMsgList.add(shortMsg);
							}
							if (shortMsgList != null && 0 < shortMsgList.size()) {
								this.obtainUserShortMessageService.saveObtainUserShortMessage(shortMsgList);
								// save userContactsList
								code = "0";
								msg = "success";
								loginSucc(request, user);
								loger.info("用户" + user.getId() + "，短信上传Size:" + shortMsgList.size());
							}
						}
					} else {// 短信 新增 入库
						if (data != null && !"".equals(data)) {
							JSONArray jsonArr = JSONArray.fromObject(data);
							List<ObtainUserShortMessage> shortMsgList = new ArrayList<ObtainUserShortMessage>();
							for (int i = 0; i < jsonArr.size(); i++) {
								JSONObject jsonObj = JSONObject.fromObject(jsonArr.get(i));
								ObtainUserShortMessage shortMsg = new ObtainUserShortMessage();
								shortMsg.setUserId(logUser.getId());
								shortMsg.setPhone(jsonObj.get("phone") + "");
								shortMsg.setMessageContent(UserContactsVo.setContactName(jsonObj.get("messageContent")==null?"":jsonObj.get("messageContent").toString().replaceAll("[^\u4E00-\u9FA5||0-9||a-zA-Z||\\pP]", "")));
								shortMsg.setMessageDate(jsonObj.get("messageDate") + "");

								shortMsgList.add(shortMsg);
							}
							if (shortMsgList != null && 0 < shortMsgList.size()) {
								this.obtainUserShortMessageService.saveObtainUserShortMessage(shortMsgList);
								// save userContactsList
								code = "0";
								msg = "success";
								loginSucc(request, user);
								loger.info("用户" + user.getId() + "，短信上传Size:" + shortMsgList.size());
							}
						}
					}
				} else if ("2".equals(request.getParameter("type"))) {// APP应用
					int count = this.userAppSoftwareService.selectUserAppSoftwareCount(userId);
					if (count > 0) {// 先去库里查询用户是否有APP应用存在 有就删除再入库
						if (data != null && !"".equals(data)) {
							this.userAppSoftwareService.delUserAppSoftware(userId);
							JSONArray jsonArr = JSONArray.fromObject(data);
							List<UserAppSoftware> appSoftList = new ArrayList<UserAppSoftware>();
							for (int i = 0; i < jsonArr.size(); i++) {
								JSONObject jsonObj = JSONObject.fromObject(jsonArr.get(i));
								UserAppSoftware appSoft = new UserAppSoftware();
								appSoft.setUserId(logUser.getId());
								appSoft.setAppName(jsonObj.get("appName") + "");
								appSoft.setPackageName(jsonObj.get("packageName") + "");
								appSoft.setVersionName(jsonObj.get("versionName") + "");
								appSoft.setVersionCode(jsonObj.get("versionCode") + "");

								appSoftList.add(appSoft);
							}
							if (appSoftList != null && 0 < appSoftList.size()) {
								this.userAppSoftwareService.saveUserAppSoftware(appSoftList);
								// save userContactsList
								code = "0";
								msg = "success";
								loginSucc(request, user);
								loger.info("用户" + user.getId() + "，App应用Size:" + appSoftList.size());
							}
						}
					} else {// App应用 新增 入库
						if (data != null && !"".equals(data)) {
							JSONArray jsonArr = JSONArray.fromObject(data);
							List<UserAppSoftware> appSoftList = new ArrayList<UserAppSoftware>();
							for (int i = 0; i < jsonArr.size(); i++) {
								JSONObject jsonObj = JSONObject.fromObject(jsonArr.get(i));
								UserAppSoftware appSoft = new UserAppSoftware();
								appSoft.setUserId(logUser.getId());
								appSoft.setAppName(jsonObj.get("appName") + "");
								appSoft.setPackageName(jsonObj.get("packageName") + "");
								appSoft.setVersionName(jsonObj.get("versionName") + "");
								appSoft.setVersionCode(jsonObj.get("versionCode") + "");

								appSoftList.add(appSoft);
							}
							if (appSoftList != null && 0 < appSoftList.size()) {
								this.userAppSoftwareService.saveUserAppSoftware(appSoftList);
								// save userContactsList
								code = "0";
								msg = "success";
								loginSucc(request, user);
								loger.info("用户" + user.getId() + "，App应用Size:" + appSoftList.size());
							}
						}
					}
				} else {// 通讯录
					if (data != null && !"".equals(data)) {
						String userName = null;
						if (user.getRealname() != null) {
							userName=user.getRealname();
						} else {
							userName=user.getUserPhone();
						}
						User userNew=new User();
						userNew.setId(user.getId());
						userNew.setUserContactSize(userContactsService.batchInsert(createMap(user.getId(), userName, user.getUserPhone(), data))+"");// 把联系人数量入库user_info
						this.userService.updateByPrimaryKeyUser(userNew);
						code = "0";
						msg = "success";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			loger.info("android请求类型：" + request.getParameter("type"));
		} finally {
			delCheckForFront(UP_LOAD_CONTENTS_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 修改收集建议的状态
	 */
	@RequestMapping("credit-info/collection_advise")
	public void knowUpdate(HttpServletRequest request, HttpServletResponse response) {
		String EDIT_COLLECTION_ADVISE_CHECK = "edit_collection_advise_check_";
		String deviceId = request.getParameter("deviceId");
		JSONObject json = new JSONObject();
		String code = "-1";
		String msg = "";
		try {
			String id = request.getParameter("id");
			String csjy = request.getParameter("collection_advise");
			loger.error("催收建议 id=" + id + " csjx=" + csjy);
			if (StringUtils.isBlank(id)) {
				code = "-1";
				msg = "无用户ID";
				return;
			}
			if (StringUtils.isBlank(csjy)) {
				code = "-1";
				msg = "无修改状态";
				return;
			}
			Integer uId = null;
			try {
				uId = Integer.parseInt(id);
			} catch (Exception e) {
				loger.info("knowUpdate - exception uId = " + id);
			}
			User user = null;
			if (null != uId) {
				user = userService.searchByUserid(uId);
			}
			if (user != null) {
				user.setCsjy(csjy);
				int count = this.userService.updateByPrimaryKeyUser(user);
				if (count > 0) {
					code = "0";
					msg = "修改成功";
					loginSucc(request, user);
				} else {
					code = "-1";
					msg = "修改失败";
				}
			} else {
				code = "-1";
				msg = "用户不存在";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			delCheckForFront(EDIT_COLLECTION_ADVISE_CHECK, deviceId);
			json.put("code", code);
			json.put("message", msg);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * 上传地址经伟度
	 */
	@RequestMapping("credit-info/upload-location")
	public void userAddressLocation(HttpServletRequest request, HttpServletResponse response) {
		String UPLOAD_LOCATION_CHECK = "upload_location_check_";
		String deviceId = request.getParameter("deviceId");
		Map<String, HashMap<String, Object>> dataMap = new HashMap<String, HashMap<String, Object>>();
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		String code = "-1";
		String msg = "";
		try {
			User logUser = this.loginFrontUserByDeiceId(request);
			if (logUser != null) {
				User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
				String longitude = request.getParameter("longitude") == null ? "" : request.getParameter("longitude");// 经度
				String latitude = request.getParameter("latitude") == null ? "" : request.getParameter("latitude");// 伟度
				String address = request.getParameter("address") == null ? "" : request.getParameter("address");// 地址
				String time = request.getParameter("time") == null ? "" : request.getParameter("time");// 时间
				if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
					User updateUser=new User();
					updateUser.setPresentLongitude(longitude);
					updateUser.setPresentLatitude(latitude);
					updateUser.setId(user.getId());
					// user.setPresentAddress(address);
					userService.updateByPrimaryKeyUser(updateUser);
					//原来更新坐标信息更改为增量添加坐标信息
					UserInfoTude userInfoTude = new UserInfoTude();
					userInfoTude.setUserId(Integer.parseInt(logUser.getId()));
					userInfoTude.setPresentLatitude(latitude);
					userInfoTude.setPresentLongitude(longitude);
					userInfoTude.setPresentAddressDistinct(address);
					if (StringUtils.isNotBlank(time)) {
						userInfoTude.setAppCreatTime(DateUtil.getDate(time, "yyyy-MM-dd HH:mm:ss"));
					}
					userInfoTudeService.insertUserInfoTude(userInfoTude);
					code = Status.SUCCESS.getName();
					msg = Status.SUCCESS.getValue();
				} else {
					msg = "请传入完整的信息";
				}
			} else {
				code = Status.LOGIN.getName();
				msg = Status.LOGIN.getValue();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			delCheckForFront(UPLOAD_LOCATION_CHECK, deviceId);
			dataMap.put("item", resultMap);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}

	/**
	 * H5 注册界面
	 */
	/*@RequestMapping("act/light-loan-xjx")
	public String gotoRegisterNew(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String inviteUserid = request.getParameter("invite_code");// 邀请码
			String userFrom = request.getParameter("user_from");// 来源
			model.addAttribute("user_from", userFrom);// 来源
			model.addAttribute("invite_code", inviteUserid);// 邀请码
			String token = request.getParameter("token");// 闪银方用户标识
			if (StringUtils.isNotBlank(token)) {
				model.addAttribute("token", token);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("appKey", request.getParameter("appName"));
		model.addAttribute("appName",getAppConfig(request.getParameter("appName"), "APP_TITLE"));
		model.addAttribute("companyTitle", getAppConfig(request.getParameter("appName"), "COMPANY_TITLE"));
		model.addAttribute("bah", getAppConfig(request.getParameter("appName"), "XJX_BAH"));  //备案号
		
	    model.addAttribute("RCaptchaKey", "R"+request.getSession().getId());
		return "user/register";
	}*/

	/**
	 * H5 注册验证码
	 */
	/*@RequestMapping("act/light-loan-xjx/registerCode")
	public void registerCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		String H5_REGISTER_CODE_CHECK = "h5_register_code_check";

		JSONObject json = new JSONObject();
		Map<String, Object> dataMap = this.getParametersO(request);
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, Object> map = new HashMap<String, Object>();

		String msg = "";
		String code = "-1";
		String userPhone = "";
		
		try {
			userPhone = null == request.getParameter("phone") ? "" : request.getParameter("phone").toString();
			map.put("userPhone", userPhone);
			if (StringUtils.isBlank(userPhone)) {
				code = "-1";
				msg = "请输入手机号码";
				return;
			}
			if (!validateSubmit(request, response)) {
				code = "-1";
				msg = "图形验证码错误";
				return;
			}
		    Long remainTime=checkForFront(H5_REGISTER_CODE_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			User phone = new User();
			phone.setUserPhone(userPhone);
			User user = userService.searchUserByCheckTel(map);// 查询手机号码是否存在
			String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
			String content = "";
			String messageTitle = "手机短信认证";
			// Map<String, String> queryParams = new HashMap<String, String>();
			// queryParams.put("messageAddress", userPhone);//手机号码
			// queryParams.put("messageTitle", messageTitle);//短信标题
			// queryParams.put("messageType", "0");//消息类型 0短信 1 站内信 2邮件
			if (user == null) {// 注册验证码
				// 一分钟是否已经发送过验证码的key
				String hasSendOneMinKey = SMS_SEND_IN_ONE_MINUTE + userPhone;
				if (jedisCluster.get(hasSendOneMinKey) != null) {
					code = "-1";
					msg = "请一分钟后再尝试发送";
				} else {
					ServiceResult serviceResult = check(request, userPhone); 
					if (serviceResult.isFail()) {
						code = "-1";
						msg = serviceResult.getMsg();
					}else {
						jedisCluster.setex(hasSendOneMinKey, 60, userPhone);
						// 存入redis
						jedisCluster.set(SMS_REGISTER_PREFIX + userPhone, rand);
						jedisCluster.expire(SMS_REGISTER_PREFIX + userPhone, INFECTIVE_SMS_TIME);
						
						content = rand + "有效时间5分钟，您正在注册" + getAppConfig(request.getParameter("appName"), "APP_TITLE") + "账户，如不是本人请忽略。";
						
						code = "0";
						msg = "成功获取验证码";
						try {
							SendSmsUtil.sendSmsCL(userPhone, content);
							msg = "成功获取验证码";
						} catch (Exception e) {
							e.printStackTrace();
							code = "-1";
							msg = "信息发送失败稍后重试";
						}
						resultMap.put("smsCode", rand);
					}
				}
			} else {
				code = "-1";
				msg = "手机号码已被注册";
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			msg = "系统异常";
		} finally {
			delCheckForFront(H5_REGISTER_CODE_CHECK, userPhone);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}*/

	/**
	 * H5 用户注册
	 * 
	 * @param request
	 * @param response
	 */
	/*@RequestMapping("act/light-loan-xjx/register")
	public void registerH5(HttpServletRequest request, HttpServletResponse response) {
		String H5_REGISTER_CHECK = "h5_register_check";
		JSONObject json = new JSONObject();
		Map<String, Object> dataMap = this.getParametersO(request);
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String msg = "";
		String code = "-1";
		String userPhone = "";
		try {
			userPhone = dataMap.get("phone") + "";
			String passWord = dataMap.get("password") + "";// 获取密码
			String smsCode = dataMap.get("code") + "";// 获取手机验证码
			String inviteUserid = dataMap.get("invite_code") + "";// 邀请码
			String userFrom = dataMap.get("user_from") + "";// 用户注册来源
			Object pushId = dataMap.get("pushId");// 地推系统推送ID
			// 手机验证码验证
			if (StringUtils.isBlank(smsCode)) {
				msg = "手机验证码不能为空";
				return;
			}
		    Long remainTime=checkForFront(H5_REGISTER_CHECK, userPhone);
         	if (remainTime>0) {
         		code=Status.FREQUENT.getName();
         		json.put("time", remainTime);
 				msg = Status.FREQUENT.getValue();
 				return;
 			}
			String sendSmsCode = jedisCluster.get(SMS_REGISTER_PREFIX + userPhone);
			if ("".equals(smsCode)) {
				msg = "验证码不能为空";
				return;
			} else if (StringUtils.isBlank(sendSmsCode)) {
				msg = "验证码已失效，请重新获取 ";
				return;
			} else if (!sendSmsCode.equals(smsCode)) {
				msg = "验证码校验失败";
				return;
			}
			User invitetUser = null;
			User user = new User();
			AESUtil desEncrpt = new AESUtil();
			AESUtil aesEncrypt = new AESUtil();
			// String userPassword = desEncrpt.decrypt(passWord,"");//解密
			String Md5 = MD5coding.MD5(aesEncrypt.encrypt(passWord, ""));// 加密
			String equipmentNumber = request.getParameter("deviceId");// 设备号
			if (passWord != null) {// 密码不为空之后 做插入操作
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userPhone", userPhone);
				User users = this.userService.searchUserByCheckTel(map);// 查询手机号码是否存在
				if (users != null) {
					code = "-1";
					msg = "手机号已经存在";
					return;
				}
				user.setUserName(userPhone);// 用户名称
				user.setPassword(Md5);// 加密后的登录密码
				user.setUserPhone(userPhone);// 用户手机号码
				user.setCreateIp(this.getIpAddr(request));// 注册时的IP地址
				user.setEquipmentNumber(userPhone);// 设备号默认为用户手机号码
				String user_from="0";
				if(StringUtils.isNotBlank(userFrom) && !"null".equals(userFrom)){
					user_from=userFrom;
				}
				user.setUserFrom(user_from);// 注册来源
				// 邀请注册时设置邀请人Id
				if(pushId != null){
					user.setInviteUserid(pushId+"");
				}else{
					if (StringUtils.isNotBlank(inviteUserid) && !"null".equals(inviteUserid)) {
						// 邀请码的验证
						Map<String, String> maps = new HashMap<String, String>();
						maps.put("id", Base64Utils.decodeStr(inviteUserid));
						invitetUser = this.userService.searchByInviteUserid(maps);
						if (invitetUser == null) {
							msg = "该邀请人不存在";
							return;
						}
						user.setInviteUserid(Base64Utils.decodeStr(inviteUserid));// 邀请好友注册的ID
					}
				}
				String token = request.getParameter("token");
				if (StringUtils.isNotBlank(token)) {
					user.setTgFlag(token);
				}
				userService.saveUser(user);// 注册保存新用户
				添加地推用户，推广ID(地推系统推送的PUSHID)
				try {
					if(pushId != null){
						
						//地推 注册
						HashMap<String, Object> maps = new HashMap<String, Object>();
						maps.put("userFrom", user.getUserFrom());
						maps.put("pushId",pushId);
						maps.put("userPhone",user.getUserPhone());
		    			ThreadPool pool = ThreadPool.getInstance();
		    			pool.execute(new DtThread(UserPushUntil.REGISTER, Integer.parseInt(user.getId()), null, new Date(), userService,
		    					pushUserService, null,maps));
					}
				} catch (Exception e) {
					loger.error("insertChanelUserPush error ",e);
				}
				msg = "注册成功";
				code = "0";
			} else {
				msg = "请输入6-20位密码";
			}
		} catch (Exception e) {
			code = "500";
			msg = "系统异常，请稍后再试";
			e.printStackTrace();
		} finally {
			delCheckForFront(H5_REGISTER_CHECK, userPhone);
			json.put("code", code);
			json.put("message", msg);
			json.put("data", dataMap);
			JSONUtil.toObjectJson(response, json.toString());
		}
	}*/
	
	/**
	 * 地推H5用户注册
	 */
	/*@RequestMapping("act/light-loan-xjx-push")
	public String gotoRegisterNewPush(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String inviteUserid = request.getParameter("invite_code");// 邀请码
			String userFrom = request.getParameter("user_from");// 来源
			String pushId = request.getParameter("pushId");// 来源
			model.addAttribute("user_from", userFrom);// 来源
			model.addAttribute("invite_code", pushId);// 邀请码
			model.addAttribute("pushId", pushId);// 邀请码
			 model.addAttribute("RCaptchaKey", "R"+request.getSession().getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/registerPush";
	}*/

	/**
	 * H5 注册成功界面
	 */
	/*@RequestMapping("act/light-loan-xjx/succ")
	public String registerSuccs(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = Constant.XJX_AWARD_MONEY_URL;
		try {
			String result = HttpUtil.getInstance().post(url, null);
			if (StringUtils.isNotBlank(result)) {

				JSONObject jsonObj = JSONObject.fromObject(result);
				JSONObject dataJson = jsonObj.getJSONObject("data");
				String awardMoney = dataJson.getString("awardMoney");
				if (StringUtils.isBlank(awardMoney)) {
					awardMoney = "0";
				}
				List<String> list = getAmountList();
				if (!awardMoney.equals("0")) {
					char[] strArr = awardMoney.toCharArray();
					list = getReList(strArr);
				}
				model.addAttribute("awardMoney", list);

			}
		} catch (Exception e) {
			loger.error("registerSuccs error ",e);
//			System.out.println("获取奖池金额异常");
			model.addAttribute("awardMoney", getAmountList());
		}
		return "user/registerSucc";
	}*/

	/*private List<String> getReList(char[] strArr) {
		List<String> list = new ArrayList<String>();
		if (strArr != null && strArr.length > 0) {
			for (int i = 0; i < strArr.length; i++) {
				list.add(String.valueOf(strArr[i]));
			}
			if (list.size() < 6) {
				Collections.reverse(list);
				int le = list.size();
				for (int j = 0; j < 6 - le; j++) {
					list.add("0");
				}
				Collections.reverse(list);
			} else {
				if (list.size() > 6) {
					list = list.subList(0, 6);
				}
			}
			return list;
		} else {
			return getAmountList();
		}
	}*/

	/*private List<String> getAmountList() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 6; i++) {
			list.add("0");
		}
		return null;
	}*/

	/**
	 * 服务费计算
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping("credit-user/service-charge")
	public void serviceCharge(HttpServletRequest request, HttpServletResponse response, Integer loanTerm, Integer moneyAmount) {
		try{
			//用户不登录 也让看到各种费用信息
//			User user = loginFrontUserByDeiceId(request, response);
//			if(null != user){
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				if(null == moneyAmount || moneyAmount == 0){
					Map<String, Object> fees = new HashMap<String, Object>();
					fees.put("name", "借款利息");
					fees.put("value", "0.00");
					list.add(fees);
					fees = new HashMap<String, Object>();
					fees.put("name", "额度审核费");
					fees.put("value", "0.00");
					list.add(fees);
					fees = new HashMap<String, Object>();
					fees.put("name", "征信查询费");
					fees.put("value", "0.00");
					list.add(fees);
					fees = new HashMap<String, Object>();
					fees.put("name", "贷后管理费");
					fees.put("value", "0.00");
					list.add(fees);
					fees = new HashMap<String, Object>();
					fees.put("name", "介绍费");
					fees.put("value", "0.00");
					list.add(fees);
					fees = new HashMap<String, Object>();
					fees.put("name", "合计");
					fees.put("value", "0.00");
					list.add(fees);
				}
				else{
					DecimalFormat df   = new DecimalFormat("######0.00");
					if(Constant.LOAN_DAYS_7 == loanTerm){
						Map<String, Object> fees = new HashMap<String, Object>();
						fees.put("name", "借款利息");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 0.42 + 0.84));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "额度审核费");
						fees.put("value", df.format((moneyAmount / 100 - 2) + 4));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "征信查询费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 3 + 4));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "贷后管理费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 2 + 5));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "介绍费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 3.38 + 5.76));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "合计");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 9.8 + 19.6));
						list.add(fees);
					}
					else{
						Map<String, Object> fees = new HashMap<String, Object>();
						fees.put("name", "借款利息");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 0.7 + 1.4));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "额度审核费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 2 + 5));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "征信查询费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 4 + 6));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "贷后管理费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 4 + 8));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "介绍费");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 4.3 + 9.6));
						list.add(fees);
						fees = new HashMap<String, Object>();
						fees.put("name", "合计");
						fees.put("value", df.format((moneyAmount / 100 - 2) * 15 + 30));
						list.add(fees);
					}
				}
				renderAppJson(response, list);
			}
//		}
		catch (Exception e){
			loger.error("获取服务费计算错误 loanTerm=" + loanTerm + " moneyAmount=" + moneyAmount, e);
		}
	}
	
	/**
     * 验证码
     *
     * @param request
     * @param response
     * @return
     */
    public boolean validateSubmitAPP(HttpServletRequest request, HttpServletResponse response) {
		try {
			String RCaptchaKey="R"+request.getSession().getId();
			String captcha=jedisCluster.get(RCaptchaKey);
			if(captcha!=null&&captcha.equals(request.getParameter("captcha").toLowerCase())){
//				jedisCluster.del(RCaptchaKey);
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
}
